Académique Documents
Professionnel Documents
Culture Documents
Objectives: Exposure to basics of object oriented mode, C++ programming and I/O
in C++
INTRODUCTION: Differences between C and C++, the Object Oriented Technology,
Disadvantage of
Conventional Programming, Concepts of Object Oriented Programming, Advantages
of OOP, Structure
of a C++ Program, Header Files and Libraries.
INPUTAND OUTPUT IN C++: Introduction, Streams In C++ and Stream Classes,
Pre-Defined Streams, Stream Classes, 'Formatted and Unformatted Data,
Unformatted Console I/O Operations, Member Functions of istream Class, Formatted
Console I/O Operations, Bit Fields, Flags without Bit Field, Manipulators, User
Defined Manipulators.
Following are the differences Between C and C++ :
C
C++
1. C is Procedural Language.
8. In C++
10. In C, we can call main() Function through 10. In C++, we cannot call main()
other Functions
Function through other functions.
11. C++ allows the declaration of
11. C requires all the variables to be defined
variable anywhere in the scope i.e at
at the starting of a scope.
time of its First use.
12. No inheritance is possible in C.
Features of
OOPs
The prime
purpose of
C++
Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in
program without presenting the details.
For example, a database system hides certain details of how data is stored and
created and maintained. Similar way, C++ classes provides different methods to the
outside world without giving internal detail about those methods and data.
Encapsulation
Encapsulation is placing the data and the functions that work on that data in the
same place. While working with procedural languages, it is not always clear which
functions work on which variables but object-oriented programming provides you
framework to place the data and the relevant functions together in the same object.
Inheritance
One of the most useful aspects of object-oriented programming is code reusability.
As the name suggests Inheritance is the process of forming a new class from an
existing class that is from the existing class called as base class, new class is
formed called as derived class.
This is a very important concept of object-oriented programming since this feature
helps to reduce the code size.
ypes of Inheritance
In C++, we have 5 different types of Inheritance. Namely,
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual Inheritance)
Single Inheritance
In this type of inheritance one derived class inherits from only one base class. It is
the most simplest form of Inheritance.
Multiple Inheritance
In this type of inheritance a single derived class may inherit from two or more than
two base classes.
Hierarchical Inheritance
In this type of inheritance, multiple derived classes inherits from a single base class.
Multilevel Inheritance
In this type of inheritance the derived class inherits from a class, which in turn
inherits from some other class. The Super class for one, is sub class for the other.
Polymorphism
The ability to use an operator or function in different ways in other words giving
different meaning or functions to the operators or functions is called polymorphism.
Poly refers to many. That is a single function or an operator functioning in many
ways different upon the usage is called polymorphism.
Overloading
The concept of overloading is also a branch of polymorphism. When the exiting
operator or function is made to operate on new data type, it is said to be
overloaded.
Advantages of OOPs
It is easy to maintain and modify existing code as new objects can be created
with small differences to existing ones.
objects, methods, instance, message passing, inheritance are some
important properties provided by these particular languages
encapsulation, polymorphism, abstraction are also counts in these
fundamentals of programming language.
It implements real life scenario.
In OOP, programmer not only defines data types but also deals with
operations applied for data structures.
2. This is entry point for all the function. Each and every method is called
indirectly through main.
3. We can create class objects in the main.
4. Operating system call this function automatically.
Header Files and Libraries.
cassert (assert.h)
This library contains only the function assert. You use
assert(assertion);
to test the validity of an assertion. If assertion is false, assert writes an error
message and terminates program execution. You can disable all occurrences
of assert in your program by placing the directive
#define NDEBUG
before the include directive.
cctype (ctype.h)
Most functions in this library classify a given ASCII character as a letter, a digit, and
so on. Two other functions convert letters between uppercase and lowercase.
The classification functions return a true value if ch belongs to the specified group;
otherwise they return false.
isalnum(
Returns true if ch is either a letter or a decimal digit
ch)
isalpha(
Returns true if ch is a letter
ch)
iscntrl(c
Returns true if ch is a control character (ASCII 127 or 0 to 31)
h)
isdigit(c
Returns true if ch is a decimal digit
h)
isgraph(
Returns true if ch is printable and nonblank
ch)
islower(
Returns true if ch is a lowercase letter
ch)
isprint(c
Returns true if ch is printable (including blank)
h)
ispunct(
Returns true if ch is a punctuation character
ch)
isspace( Returns true if ch is a whitespace character: space, tab, carriage return,
ch)
new line, or form feed
isupper(
Returns true if ch is an uppercase letter
ch)
isxdigit(
Returns true if ch is a hexidecimal digit
ch)
toascii(c
Returns ASCII code for ch
h)
tolower( Returns the lowercase version of ch if ch is an uppercase letter; otherwise
ch)
returns ch
toupper( Returns the uppercase version of ch if ch is a lowercase letter; otherwise
ch)
returns ch
cfloat (float.h)
Defines named constants that specify the range of floating-point values.
climits (limits.h)
Defines named constants that specify the range of integer values.
cmath (math.h)
The C++ functions in this library compute certain standard mathematical functions.
These functions are overloaded to accomodatefloat, double, and long double.
Unless otherwise indicated, each function has one argument, with the return type
being the same as the argument type (either float, double, or long double).
acos Returns the arc cosine
asin Returns the arc sine
atan Returns the arc tangent
atan
Returns the arc tangent x/y for arguments x and y
2
ceil Rounds up
cos Returns the cosine
cos
Returns the arc cosine
h
exp Returns ex
fabs Returns the absolute value
floo
Rounds down
r
fmo
Returns x modulo y for arguments x and y
d
frex For arguments x and eptr, where x = m * 2e, returns m and sets eptr to point
p
to e
ldex
Returns x * 2e , for arguments x and e
p
log Returns the natural log
log1
Returns the log base 10
0
mod For arguments x and iptr, returns the fractional part of x and sets iptr to point
f
to the integer part of x
pow Returns xy , for arguments x and y
sin Returns the sine
sinh Returns the hyperbolic sine
sqrt Returns the square root
tan Returns the tangent
tan
Returns the hyperbolic tangent
h
cstdlib (stdlib.h)
abort Terminates program execution abnormally
abs
Returns the absolute value of an integer
atof
Converts a string argument to floating point
atoi
Converts a string argument to an integer
exit
Terminates program execution
rand() Generates an unsigned int between 0 and RAND_MAX, a named constant
defined in cstdlib header file
exception() throw();
virtual -exception() throw();
exception &operator=(const exception %exc) throw();
virtual const char *what() const throw();
}
fstream (fstream.h)
Declares the C++ classes that support file I/O.
iomanip (iomanip.h)
The manipulation in this library affect the format of steam operations. Note that
iostream contains additional manipulators.
setbase(b)
Setts number base to b = 8, 10, or 16
setfill(f)
Sets fill character to f
setprecision(n) Sets floating-point precision to integer n
setw(n)
Sets field width to integer n
iostream (iostream.h)
The manipulators in this library affect the format of stream operations. Note that
iomanip contains additional manipulators.
dec
Tells subsequent operation to use decimal representation
end1
Inserts new-line character \n and flushes output stream
ends
Inserts null character \0 in an output stream
flush
Flushes an output stream
hex
Tells subsequent I/O operations to use hexadecimal
representation
oct
Tells subsequent I/O operation to use octal representation
ws
Extracts whitespace characters on input stream
string
This library enables you to manipulate C++ strings. Described here is a selection of
the functions that this library provides. In addition, you can use the following
operators with C++ strings: =, +, ==, !=, <, <=, >, >=, <<, and >>. Note that
positions within a string begin at 0.
erase()
Makes the string empty
erase(pos, len)
Removes the substring that begins at position pos and
contains len characters
find(subString)
Returns the position of a substring within the string
length()
Returns the number of characters in the string
(same as size)
replace(pos, len, str) Replaces the substring that begins at position
pos and contains len characters with the string str
size()
Returns the number of characters in ths string
(same as length)
substr(pos, len)
Returns the substring that begins at position pos
and contains len characters
INPUTAND OUTPUT IN C++: Introduction, Streams In C++ and Stream Classes,
Pre-Defined Streams, Stream Classes, Formatted and Unformatted Data,
Unformatted Console I/O Operations, Member Functions of istream Class, Formatted
Console I/O Operations, Bit Fields, Flags without Bit Field, Manipulators, User
Defined Manipulators.
The first thing you may notice about this hierarchy is that it uses multiple
inheritance (that thing we told you to avoid if at all possible). However, the iostream
library has been designed and extensively tested in order to avoid any of the typical
multiple inheritance problems, so you can use it freely without worrying.
Streams
The I/O in C++ is implemented with streams. Abstractly, a stream can be
thought of as a sequence of bytes of infinite length that is used as a buffer
to hold data that is waiting to be processed.
Typically we deal with two different types of streams. Input streams are used to hold
input from a data producer, such as a keyboard, a file, or a network. For example,
the user may press a key on the keyboard while the program is currently not
expecting any input. Rather than ignore the users keypress, the data is put into an
input stream, where it will wait until the program is ready for it.
Conversely, output streams are used to hold output for a particular data consumer,
such as a monitor, a file, or a printer. When writing data to an output device, the
device may not be ready to accept that data yet -- for example, the printer may still
be warming up when the program writes data to its output stream. The data will sit
in the output stream until the printer begins consuming it.
Some devices, such as files and networks, are capable of being both input and
output sources.
Input/output in C++
Although the ios class is generally derived from ios_base, ios is typically the most
base class you will be working directly with. The ios class defines a bunch of stuff
that is common to both input and output streams. Well deal with this stuff in a
future lesson.
The istream class is the primary class used when dealing with input streams. With
input streams, the extraction operator (>>) is used to remove values from the
stream. This makes sense: when the user presses a key on the keyboard, the key
code is placed in an input stream. Your program then extracts the value from the
stream so it can be used.
The ostream class is the primary class used when dealing with output streams.
With output streams, the insertion operator (<<) is used to put values in the
stream. This also makes sense: you insert your values into the stream, and the data
consumer (eg. monitor) uses them.
The iostream class can handle both input and output, allowing bidirectional I/O.
Finally, there are a bunch of classes that end in _withassign. These stream classes
are derived from istream, ostream, and iostream (respectively) with an assignment
operator defined, allowing you to assign one stream to another. In most cases, you
wont be dealing with these classes directly.
Standard streams in C++
A standard stream is a pre-connected stream provided to a computer program by
its environment. C++ comes with four predefined standard stream objects that
have already been set up for your use. The first two, you have seen before:
1. cin -- an istream_withassign class tied to the standard input (typically the
keyboard)
2. cout -- an ostream_withassign class tied to the standard output (typically the
monitor)
3. cerr -- an ostream_withassign class tied to the standard error (typically the
monitor), providing unbuffered output
4. clog -- an ostream_withassign class tied to the standard error (typically the
monitor), providing buffered output
Unbuffered output is typically handled immediately, whereas buffered output is
typically stored and written out as a block. Because clog isnt used very often, it is
often omitted from the list of standard streams.
A basic example
Heres an example of input and output using the standard streams:
#include <iostream>
int main()
{
using namespace std;
// First we'll use the insertion operator on cout to print
text to the monitor
cout << "Enter your age: " << endl;
Pre-Defined Streams
iostream Library
In C Formatted I/O you have learned the formatted I/O in C by calling various
standard functions. In this Module we will discuss how this formatted I/O
library
The compilers that fully comply with the C++ standard that use the template
based header files wont need the .h extension. Please refer
to Namespaces for more information.
The iostream class hierarchy is shown below. From the base class ios, we
have a derived class:
Class
Brief description
istream
Class for stream input operation.
ostream
Class for stream output operation.
ios derived classes
So, iostream support both stream input and output. The class hierarchy is
shown below.