0% found this document useful (0 votes)
15 views152 pages

C++ Final

Uploaded by

harshearn46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views152 pages

C++ Final

Uploaded by

harshearn46
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 152

Concept of Objects & Classes

Classes and objects are one of the most important features of oop because oop always
require object and for object we have to use class.
 Class is a user defined data type.
 It is also called “Abstract Data Type” (ADT)

Encapsulation

Encapsulation refers that each and everything must be within a single unit. And that
single unit is called “class” or wrapping of data and function into a single unit is called
Encapsulation and that concept is implemented by classes.

 Oop always require object and object always require class.


 Class is almost similar to the Structure of C Language.

Syntax of class

Key word class <class name > user defined class name
{
member of a class >
This block contains data member and member function.
}

Block diagram of class

CLASS

M
Data Member Instance
E Variable
M
B Data Member

E
R Data Member

S M
E
M
Member Function
B
Member Function
E
R
Functions S

1
CLASS:-
Class always contain two types of elements .These are called members of a class.
The two type of member are:-
1 Data member
2 Member function

1. Data member: - (also called Instance Variable)


It specifies the properties or characteristics or behavior of an object.

2. Member function
Specifies the functioning that can perform by object.

 Class is also called “CONTAINER” because it behaves like a container and it contain
data member and member functions.
 Class contains number of member functions and no. of Data Members.

Syntax of any class:

class <class name >


{
private access specifier:

Data members;
Member function;

protected access specifiers:

Data member;
Member function

public access specifiers:

Data member;
Member function;
};

Points regarding to this class syntax:


 „Class‟ keyword is used to define a class.
 „Class‟ keyword preceded by name of a class which is user defined.
(This name
 Space not allowed, digits can be there but not at start.
 Special symbol not allowed.
Only underscore (-) allowed
Always start with character.

Access Specifiers
Private, protected, public

 These are key words.


 These are used to allow or assign the permission on the member so that either they can
access outside of a class or not (for data security purpose) .

2
 If we do not specify these access specifiers then by default they are of private category.
 Private category member does not allow members to be accessed outside of a class, even
not with the object.
 Access specifiers always postfix with colon (:) sign.
 Once we have assign access specifiers, then all remaining members will become of its
category.
If we change this affect so now again we have to specify new access specifiers.
 So consider or use following rule:
o While defining a class, first define all members, which we want to declare as
private because they are by default private.
o Then define protected or public member with access specifier.
 Class always terminated by semicolon (;)
 Multiple and multiple time access specifier can be used.
 A program can contain multiple classes.
 A class can also contain another class that is called nested class or this concept is called
nesting of classes.

Data members cannot be initialized with in a class because memory is not


allocated yet, when object will create then memory will be allocated.

OBJECT:-

Definition: - Object is a variable of class.


 Object is a real world entity
 When we declare variable of a class this is called an object.
 Object is a representation of a class.
 Object is an instance of a class
 Object is always used to access the member of a class but they must be public.
 Class functioning is always used by object.
 Multiple objects can be there for a single class.
 Object makes any programming as oop
 All tasks are done with help of an object.
 An object can be treated as a normal variable.
 An object is a combination of properties and functioning.

Syntax for declaring object.


1. class <class name> <object name>;

Optional keyword name of class name of an object


Here <> bracket indicate that it will specify by user.

 class keywords is an optional (may be used or not)

2. Objects can also be declared while defining the class at the time of terminating class (;)
Syntax:

class demo
{

3
} ob1, ob2, ob3, ------------- ;

 Multiple objects can also be defined.


 Each object will represent like an individual entity.
 Object can be created any where in program.

According to declaration object can be categorized in two categories.


1. Local object
2. Global objects

1 Local object:-
 Which is defined with in any unit (like in function or block)
 It cannot be used anywhere it can only access with in defined block.

2. Global object:-
 Which is defined always outside of any unit?
 It can be accessed any where in the program or in any unit.
 Change in global object affect entire program.
Suppose we want to write a program in c++ to add two values.
Solution

#include<iostream>h>
#include<conio.h>
void main()
{
int a,b, c;
clrscr();
cout<<”\n enter first value”;
cin >>a;
cout<<”\n enter second value”;
cin >>b;
c= a+b;
cout <<”\n sum is ”<<c;
getch();
}

 This program is an exact correct but it is not according to concepts of oop.


 At least every c++ or oop program contains class, object, encapsulation and data
abstraction.
 So here, to solve this problem an object must be there which can add two values itself
which provide the member variables and member functioning .
 Here, we will create a class addition named which contain three data members and three
number functions for input, process and output (input, sum and display, named) here
sum is a process.
 input () will perform the task of taking values from user.
 sum () will add values input by user.
 display () function will display these values on

4
#include <iostream .h>
#include<conio.h>
class addition
{
int a, b, c;
public :
void input()
{
cout <<”\n enter first value”;
cin >>a;
cout<<”\n enter second value”;
cin >>b;
}
void sum ()
{
c= a+b;
}

void display()
{
cout <<”\n first value is -:”<<a;
cout <<”\n second value is ;-”<<b;
cout<<”\n sum is :-”<<c;
}
};

void main()
{
addition s;
clrscr();
s.input();
Description about the program s.sum ();
s.display();
 Here addition is a class. getch();
 s is an object. }
 class implementing concept of encapsulation.
 Entire object s implementing data abstractive and data hiding because by s we cannot
justify how values are inputting and displaying output.

Data binding is also there.


Sum () function adding two values a and b in c and these a & b are input by user
in input() function, so no need pass these values as an argument because these a, b, and c are
always available within function, called data binding.
Means data are already linked with functions, values automatically passed (available to function,
but these data members must be of class members.

So for implementing any type of functioning we have to create object for this task which contain
various function to perform task.

5
E.g.
Write a program in c++ to find out the factorial of a given no.

#include<iostream.h>
#include<conio.h>

class factorial
{
int n, f;
public :
void input()
{
cout <<”\n enter any no.”;
cin >>n;

void fact()
{
int i ;
f=1;

for (i = 1; i<=n; i++)


f = f*I;
}
void display()
{
cout <<”\n the factorial of “<< n<<”is - : <<f;
}
};

void main ()
{
factorial d;
d input ();
d. fact();
d. display ();
getch();
}

dot operator ;=> (.)


This operator is used to access the (public) member of a class outside of a class with object.

Syntax
Object. Member name;

Member can be of any data member or member function.

Public Access Specifiers


Public keyword is used so that these members can be accessed outside of a class with
object because by default (if we not specify) they are of private category and private member
cannot be accessed outside of a class so our program cannot be run.
If we want we can also make our data member as public but it will reduce the security of
data. Because of public these member will access outside of class so directly they can access
outside of class with object so no need to define function.

6
Our program like this.
void main ()
{
addition s;
clrscr();
cin>>s.a;
cin >>sb;
s.c = s.a+s.b;
cout<<endl<<s.c;
getch();
}

 If we write program like this then no any concept of oop can be implemented.
 This program can also be written simply just like c program.
void main()
{
int a, b, c;
clrscr();
cin>>a;
cin>>b;
cout<<a;
cout<<b;
cout <<c;
getch();
}

So we do not make data member as public because they will make our
Data member global and insecure so only member function create as public.

Nesting of Member Function


Access specifiers are used for member for outside accessing inside accessing is already
public.
Means everything within a class is available for each other.
Nesting of member function means function can call each other with in a class without
any object because they all are available for each other consider following program.

class Demo
{
int A,B,C;
void Input ()
{
cout <<”\N Enter Two Values”-:;
cin >>A>>B;
}
void Sum ()
{
C= A+B;
}
public;
void Display()
{
input ();
sum (); --Nesting Of Member Function
cout <<C;
}

7
};

void Main ()
{
clrscr();
demo D;
d.Display();
getch();
}

Here only display function is called because display () is calling input and sum both so when
we call display.
Display itself call input, so values input by user
Then sum is called, sum function will add these user inputted values and then display
function will display these values on console.

So when one member function calls another member function of a class it is called
nesting of member functions.

Drawback
Because of nesting, individual task cannot be performed means whenever we call
display, always input and sum will also called so independency will finished.

Private Member Function


Functions which are defined in the private category then these are called private member
functions.
Private functions cannot be accessed outside of class then they are always access by
public function means by nesting as in previous example, input( ) & sum ( ) both are private.

 We call public function in main () and public functions called private functions in a class.

Ques : What is the need of defining functions as private?


Ans : Sometimes it may be required that some function cannot be accessed outside, make this
function as private.
Consider following example,
 In mobile phone call we make two functions.
 count_time ( ) and display ( )
count_time ( )
This function counts the total call time and no need to give it to user because it should
be automatic. So it must be defined with in private category.

Display ( )
This function display the time, that is count by count_time ( ) function so it should be
accessed by uses so it must be in public category.
That‟s why users can get call time easily but cannot manipulate it because of private of count
time ( ) functions
 So for function privacy we make some functions as private just like data members.

E.g.> class demo


{
int a,b,c;
void input ()

8
{
cout <<”\n enter two values -”;
cin >>a>>b;
}
void sum ()
{
c= a+b;
}
public void display()
{
cout <<”\n ”<<a <,”\t”<,b;
cout <<”\n”<<c;
}
};

void main ()
{
demo d;
clrscr();
d.display();
getch();
}

Here display ( ) is a public function but input ( ) and sum ( ) are private function these
functions are called by display ( ) and display ( ) called by main function.

Array with in a class

 class can also an array as its data member like a normal variable
 class can contain any type of array
 Means for maintaining array class can also be used.
 class can contain multiple arrays.
 Member function must be there to input values in array and display these values.

Example:
class array
{
int a[10];
int i;
public: void input( )
{
cout<<”\n enter elements in array”;
for (i=0; i<10; i++)
{
cout<<”\n Enter Element”;
cin>>a[i];
}
}
void display( )
{
cout<<”\n array elements are: “ ;
for( i=0; i<01; i++)
cout<<”\t” <<a[i];
}
};

9
When Program Run, then
Input element in an array
Enter element 10
Enter element 20
Enter element 30
Enter element 40
Enter element 50
Enter element 60
Enter element 70
Enter element 80
Enter element 90
Enter element 100

Array elements are:-10 20 30 40 50 60 70 80 90 100

In this way a class can contain array as a data member, here array is only a name of class
for convenience.
Any name (valid) can be used here to represent entire array and its functioning that‟s why object
make program easy.

Array of object

When we declare an array of integer means this variable (array) can store multiple values
of integer types.
Similar to this array of an object can also be created this object time will act like group of
object so multiple time task can be performed and multiple values can be stored.

Eg.
#include<iostream .h>
#include<conio.h>
class factorial
{
int n;
long f;
public :
void input ()
{
cout <<”\n enter value -:”;
cin >>n;
}
void fact( )
{
int i;
f = 1;
for (i=1; i<=n; i++)
f=f*i;
}
void display ( )
{
cout <<‟\n factorial of ”<<n<< is :- “<<f;
}
};

void main( )

10
{
clrscr ();
factorial p [5]; - array of object
for (int I = 0; i<5; i++)
{
p[i] . input ();
p[i]. fact();
}
for (i= 0; i<5; i++)
p[i]. display();
getch();
}

Here p is called as an array of object this p will maintain 5 value and their factorial value.
In this by making array of an object multiple same task and multiple values can be
performed.

Object as a Function Argument

To perform a task, we use functions within a class. Sometime these functions may
require as other object of some class as an argument so required functioning can be performed.

As requirement when we pass values to a function as an argument similar to this an


entire object or object can also be passed to a function as an argument so required functioning
can be performed.

When we pass integer type of argument then data type and argument name is specified
like int a.
Similar to this in entire object passing the type of object means class name and its name
is passed as an argument.

Eg:
Suppose we want to display the addition of two object of same class then we define a
sum name function where one object (d1) will call it add another object (d2) will passed as an
argument named (p).
 Argument name may be changed or same.
 This sum function will add the member of this passed object and display these values this
passed object and display these values.

E.g.:
class demo
{
int a, b;
public :
void input ( )
{
cout <<”\n enter first value”;
cin >>a;
cout <<”\n enter second value”;
cin >>b;
}
void sum (demo p) - object as an argument
{
int x,y;

11
x = p.a +a;
y = p.b +b;
cout <<”\n addition of a “<<x;
cout <<”\n addition of b”<<y;
}
};

void main ()
{
demo d1, d2;
clrscr ();

d1. input();
d2. input ();
d1. sum (d2); - this passed to sum function as an argument .
getch();
}

Output:
enter first value = 10
enter second value = 20

enter first value = 100


enter second value = 200

Addition of a = 110
Addition of b = 220

 In this way object can be passed as an argument


 If we want to pass multiple object then multiple argument must be specified in the called
of functions and definition of function.
 If we want to add three object then we sum function like this define
 For n object manipulation always n-1 object will be passed because one object will call it.

void sum (demo p, demo q)


{
int x,y;
x = a + p. a +q. a;
y = b + p. a + q. b;
cout<<endl<<x;
cout<<endl<<y;
}
We call sum ( ) function like this:

d1 . sum (d2, d3);

 a and b are member of d1, because d1 calls sum ( )


 p is a copy of d2
 q is a copy d3
In this way multiple objects can also be passed to a function as an argument
 Here if any changes make in sum ( ) function in p and q then actual objects (d2 and d3)
will not affect because it is a call by value technique not call by reference.

12
Function Returning Object
As we known function return a value and function cannot return more than one value at
a time
Similar to this as per requirement function can also return entire object and because of
this, entire object will also return by function and this will catch by another object in calling
function.
But at a time only one object can be returned at a time.
So if we want to return multiple values then store this all values in an object we have to
create and return it, all values will returned, it is also a utility of returning entire object.

Consider previous example;


We want to add two objects are get added values in third object and new added values also
stored with in this returned object. So for storing these values intermediate temporary object (z)
also has to create of same class.

E.g.
#include<iostream .h>
# include<conio.h>
class demo
{
int a, b;
public;

void input ()
{
cout <<‟\n enter value of a “;
cin >>a;
cout <<”\n enter value of b”;
cin >>b;
}
void display()
{
cout<<”\n value of a “<<”a;
cout <<”\n value of b”<<b;
}
demo sum (demo p)
{
demo z; --- intermediate object
z.a = a+p.a;
z.b = b+p.a
return z; --- function sum ( ) returning object
}
};

void main ( )
{
clrsccr ();
demo d1, d2, d3;
cout <<”\n enter values for first object”:
d1. input ();
cout <<”\n enter values for second object”;
d2. input();
d3 = d1 . sum(d2); -- d2 object pass as an argument
cout <<‟\n values of first object ”;
d1. display();

13
cout <<”\n values of second object ”;
d2. display();
cout <<”\n returned object value is”;
d3. display ( );
getch( );
}

Out put:-
enter values of first object
enter value of a = 10
enter value of b = 20

enter values for second object:-


enter value of a = 100
enter value of b = 200

values of first object :-


value of a = 10
value of b = 20

values of second object :-


value of a = 100
value of b = 200

Returned object value is;


value of a = 110
value of b = 220

 Here d1 call sum ( ) function


 d2 is passed to sum ( ) as argument
 p is a copy of d2
 Intermediate z object is created.
 p object value and all value added and copied to z
 Function return z and copied to d3 object
 In this way function can return entire object.

Utility
With the help of this technique by using same functioning multiple objects can also be
added with same function definition.
This is nesting of function calling.
Here we will write
d4 = d1. sum (d2. sum (d3));

 Here first of all d2. sum (d3) will evaluate because bracket has highest priority.
 After execution of it sum function will return z that will play role of argument for d1 like
this (internally)
d4 = d1. Sum (z);
 Now again sum ( ) is called but for d1 and z which is a intermediate sum of d2 and d3
 And now sum will add d1 and z and finally both value sum will return and catch by d4.
 In this way by using nested calling technique multiple object can be manipulate by single
argument

14
Syntax for adding four object in d5

d5 = d1. sum (d2. sum (d3. sum (d4)));

d5 = d1 . sum (d2. sum (z));

d5 = d1. sum (z);

Memory Allocation for Object


As we specified that we cannot initialize class data members with in a class because no
any memory is allocated by defining a class.

When we create object then memory block is created and now we can access the member of a
class.

So whenever an object is created the memory is allocated to class members.

As we know class has two types of members

1. Data members
2. Member functions

Member function is common for all objects because same type of functioning need to
perform for all objects.

So if we create multiple objects then common members functions are created and stored
in memory only once when a class specification is declared (at compile time) all objects of that
class have access to the same area in the memory where the member functions are stored.

Separate memory block is created for every object data members so that they can
allow objects to handle or hold efficient values in their different data members.

Conclusion:-
Suppose we create n objects n objects of some class then Data members of these objects
are stored in the different memory allocations.

Where as,
Member functions of these objects are stored in the same memory area.

Object 1 object 2 object 3


Data 1 Data 1 Data 1
Data 2 Data 2 Data 2
| | |
| | |
| | |

Function Function Function

15
#include<iostream .h>
#include<conio.h>
class demo
{
int a,b, c;
public:
void input()
{
cout<<”\n enter two number”;
cin >>a>>b;
}
void sum ()
{
c= a+b;
}
void display()
{
cout<<”\n <<a”;
cout<<”\n <<b”;
cout <<”\n <<c;
}
};
void main( )
{
demo d1, d2, d3;
clrscr( );
d1. input ( );
d2 .input ( );
d3. input( );
d1. sum ( );
d2.sum( );
d3. sum ();
d1. display ( );
d2. display ();
d3 . display( );
getch();
}

16
Memory Allocation Block Diagram:-
Three Objects Are Created
Objects
d1 d2 d3

a b a b a b

void input( )
{
C O M M O N M E M O R Y A R E A FO R

cin >>a>>b;
}
FUNCTIONS

void sum ( )
{
c= a + b;
}

void display()
{
cout <<”\n”<,a;
cout<<”\n”<<b;
cout<<”\n ”<<c;
}

Features of OOP:-
All basic characteristics which define the nature of language and make language
more powerful are:

1. Class
2. Objects
3. Data abstraction
4. Data hiding
5. Encapsulation
6. Inheritance
7. Polymorphism
8. Data binding
9. Message passing

17
Description:-
Class
Classes are similar to the structure of C Language class is also known as unit.
Class combine data and function together so their representative can be created easily
Class is a user defined data type.
Class is also called as category.

Object
 Object is an real world entity (element)
 e.g. > “pen” “pencil”, car, student etc.
 Every object has their own characteristic and functioning (these defining by class)
 Object is a representative of a class.
Object is also called an instance of a class.
 Object allows using the class.
Object is a variable of a class.

Data Abstraction:-
“Summary of Data”
Abstraction refers to the way of representing only required feature without including all.
Background details and functioning are hidden, only required details are shown.
Oop allows user to only interact with the required feature rather than interact with all feature.
Class and object provide concept of abstraction because when user use object he don‟t
known the structure of object or functioning of object or element of object
Class uses the concept of data abstraction so classes also called as Abstract Data Type.

Data Hiding:-
When you use object then all task is performed by object values and quantity are also stored
by object so user can‟t access data or not visible to user that concept is called data hiding means
where data is hide from user.
Encapsulation:-
 Encapsulation refers to “each and everything must be within a single unit”
 Encapsulation is most important feature of oop.
 Encapsulation means “wrapping of data and function into a single unit (class)
 Means when we define all data and functions within a single unit and for using this
feature all the feature can be used or accessed, this is called encapsulation.

Inheritance:-
“One class can access the properties of another class this is called Inheritance.”
Inheritance refers to reusability feature programs always want that once he has write
some code then he does not want that he write this code again. OOP programming allows a new
facility where required defined code can be used number of times without rewriting it again here
inheritance refers that “one class can easily use the properties and function of another class directly”
This concept is derived from our real life where child easily use properties of parent Also known
as communication of class through inheritance we establish the relation b/ w or among classes.

Polymorphism:-
“Single Interface Multiple Task “
oop allows a special feature where we will create only single or one interface and through this
interface multiple task can be performed easily is called polymorphism.
18
Suppose we create sum name function which can add two values.
When we define this function then we have to specify the type suppose int , int then this
function can only add two integer but,
When we want to add two float or two double type values then this function cannot
work then we have to create another function for long double or for required type.
When we have to write different name of these functions then this is inconvenient
because user has to learn this all function name like sum 1, sum 2, --- so on.

To remove this problem polymorphism is there here multiple same name functions can be used
they differ by no. and type of argument.
Here are two type run time & compile time

Data Binding:-

Data binding specifying that data are already binded with functions so on need to pass
this data explicitly otherwise we have to pass argument modally but because of its concept data
or values are automatically passed to a function.
Means sum function automatically sum the values that are
There are two type; late & early

Message passing:-

Multiple objects can be there they may be of either same type or different type these
objects can also communicate with each other or they can share their values to perform any task.
So when objects share or pass their values to perform any task.
So when objects share or pass their values is called message passing

Values are passed through object when object invoke procedure of function.
So these are basic feature of oop, which make oop more efficient and better.

Benefits of OOP:-

OOP provide so many utilities to both the program and user.


 No redundancy of code (inheritance)
 Classes
 Security of data
 Easy to implement.
 Step by step solution
 Object perform task effectively.
 Secure programming
 Multiple objects can be created
 Save program develop next time
 Modularity
 Easy up gradation to functioning
 Required feature already provided (STL)
 Easy to use
 Software complexity can be easily managed
 Expansion is easy

19
Application Of Oop:-

Applications specify various areas where oop feature and concept are used.
1 Real time systems
2 Simulation (virtual environment creation)
3 Object oriented data base
4 Networking
5 Neural network creation
6 Expert system and Artificial Intelligence
7 Parallel programming
8 CAD / CAM programming

Difference b/w OOP and Procedural programming:-

Procedural OOP
1. Mainly emphasis on procedure 1. Emphasis on data.
2. Program divides into functions 2. Program divides into objects.
3. Functions share global data 3. functions share class data
4. Data move openly 4. data is fully secured
5. Functions transfer data to each 5. Data are already binded with
other functions.
6. Top down approach is used 6. Bottom up approach is used.
7. New functions cannot be included
7. New functions can be easily added.
easily
8. No data hiding. 8. Data hiding easily possible.
9. Easy communication by message
9. No easy communication
passing.
10. Easy to implement but not rule 10. Easy to implement and rule based
based programming.

 No of difference are there but major are explained as above as per requirement language can
be used.

20
Inline Function
 Our class can have number of different function. When complier compiles them, they
convert into executable code.
 And when this code executed the following task may occur:
 Save the address of instruction following the function call
 Copy argument values in stack.
 Jump to memory location of called functions.
 Execute the instructions.
 Store the return value if it has.
 Jump back to or move back to earlier (step 1) address of instruction to execute it.
 These numbers of steps occur whenever any function call; it is a so much overhead. So
we should avoid it, it can increase our program execution time
C++ provide us an alternative to avoid this, i.e. make function [inline], means
when any function is called number of times then there will be calling overhead in our
programming, it reduce the execution time to avoid or overcome this problem, concept
of Inline keyword is used.

 With inline keyword, the compiler replaces the function call statement with the function
code itself, this is called “Expansion” and this compiles the entire code.
 So code expanded at the place of function call, then no need to jump to anywhere and no
above steps will occur. So saving of time and less management and no overhead.
 Whenever function that is inline, when it is called, its copy is maintained at the place of
its calling (at time) so it is called inline.
Consider following code:-
class demo
{
int a,b,c;
public:
void input();
void display();
void sum ();
};
void demo :: input ()
{
cin>>a>>b;
}
void demo :: sum ()
{
c = a+b;
}
void demo :: display()
{
cout<<a<<b<<c;
}
void main ()
{
demo d1, d2, d3;
clrscr ();
d1. input();
d2. input();
d3 . input ();
d1. sum ();

21
d2 . sum ();
d3. sum ();
d1. display();
d2. display();
d3. display();
getch();
}
In previous diagram there is a lot of overhead in calling the function. Function called and
move again (go back) to its previous location so there is a lot of overhead or wasting of time. So
our goal is saving of time in execution.
We want that this code must be copied when it is called with in main () function as given
below:

void main ( )
{
demo d1, d2, d3;
clrscr ( );
cin>>a>>b; for d1
cin>>a>>b; for d2
cin >>a>>b; for d3
c= a+b; for d1
c= a+b; for d2
c= a+b; for d3
cout <<”\n sum is :”<<c; for d1
cout <<”\n sum is ”<<c; for d2
cout <<”\n sum is ”<<c; for d3
}

 Since this type of writing code is not possible because there is no any concept of oops so
directly it is not possible.
But we want to do so; this thing is implemented by making these all functions as
inline. If we make functions as inline then these all functions are expanded at the calling point.
Saving our execution time and reduce overhead.
 To make function inline, define it inside the class but follows its rules.
This type of coding is not seen to us, it is internal coding or internal translation. We write
our program or function as usual but if we make inline then its coding expanded inline at
their call.

Some points regarding to inline functions:-


1. Inline keywords are used to make any functions as inline before functions definition as
prefix.
2. All functions that are defining inside the class, they all are by default inline function.
3. Their copy is maintained automatically without using keywords inline.
4. Any function that defines outside of a class, it can also be defined as inline by using inline
keyword before function header definition.
5. Any function can be defined inline either it is a member of a class or non member of a
class.
6. Inline is basically a request not a command, this request either can be accepted or
rejected.
7. Inline function does not contain loop.
8. Inline function does not have any switch statement.
9. Inline function does not contain go to statement.
10. Inline function cannot be a recursive.

22
11. Inline function cannot return value; means it does not contain return statement.
12. Inline function must contain only two or four lines because if they expanded inline, it will
create more lines, more line execution will increase the overhead.
13. If above rules break, then inline gives warning, not error, that‟s why inline is a request.
14. Macro can also used at the place of inline function but macro is not really function, they
are preprocessor.
15. Inline expansion makes a program run faster because the overhead of a function call and
return is eliminated.

Drawback:-
 It takes lot off amount of memory because statements that define the inline function are
reproduced at each point where the function is called.
 Inline functions are not better for large coding functions that are often called.
 As we said that inline is a request, it always ignored when any attempt of its rule break
occur. If you satisfy its rules that it make inline.

SRO (: :) Scope Resolution Operator


Special point:-
Functions can be defined outside or inside of a class.
Quest: - Why there is a need for defining the function outside of class?
Ans: - Sometime when we define the functions inside the class then “warning” occur (why?)
This warning occurs because functions are defined inside the class and these functions
are inline by default, so if they are breaking the rule of inline then warning occurs. If we want
that warning should not occur so they define outside of class with (::) to relate this function with
class. Example:-
Concept 1:-
Functions which define with in class, they are by default Inline Function.
class demo
{
int a, b, c;
public:
void input ()
{
cin >>a>>b;
}
void display()
{
cout <<a<<b<<c;
}
void sum ( )
{
c = a + b;
}
};

Concept 2: outside defined functions are not inline, they are outline.

class demo
{
int a, b,c;
public :
void input ();
void sum ();

23
void display();
};
void demo :: input ()
{
cin >>a>>b;
}
void demo :: display ()
{
cout <<a<<b<<c;
}

void demo :: sum ()


{
c = a+b;
}

When any function defines outside of a class then its relation with classes break so error
will occur, there is a need to establish dual relationship between class with function and function
with class.

To relate class with function, declare the function within its body that is function
prototyping.

To relate function with class while defining the function name of class and SRO operator has to
be used. By using both ways function can be defined outside of class.

Concept 3:
Making an outside function inline
Any outside declared function can be defined as inline by prefixing inline key words
while its definition.
For example.

class demo
{
int a,b,c;
public:
void input ();
void display();
void sum ();
};

inline void demo :: input ()


{
cin >>a>>b;
}
inline void demo :: display ()
{
cout <<a<<b<<c;
}
inline void demo :: sum ()
{
c = a +b;
}

24
[Function will expanded when they call]
So by using these all concept we can use inline in our c++ programming.

Static Class Members

 Whenever we declare object then individual memory block is allocated for every data
members of every object, so every object contain its own value because of different
memory block.
 C++ class contains special type of members that are known as static members of a class.
 These are two types of static members “Static Members Variable” and “Static Members
Functions”.

Class

Static Member

Static Data Member Static Members Function


 Means any member variable and member function can be defined as static by prefixing
“static” key word.

Definition:-

 Static members are those members which are common for all the objects of a class.
 Only single memory block is allocated for all the objects members which are static.
 Global variables are used to hold common values, but in oop not convenient to use
global variables. At the place of global variable static members are used because of
Encapsulation.

Example of memory allocation for Non static members:

class demo
{
int a, b, c; // non static members
};
void main ( )
Memory Blocks: {
demo d1, d2, d3;
}

a b c a b c a b c

d1 object d2 object d3

Same class with static members

25
class demo
{
int a, b; // non static members
static int c; // static members
};

int demo: : c //Static Declaration outside of class


void main ()
{
demo d1, d2, d3;
}

C is a common for all objects.

Memory blocks:-

a b a b
d2 d3

Here c is allocated a different block because it is a static member and static member are common
for all the objects of class. Only one copy exists for all object if they are exist.

Some key points about static members.

1. Static data members are treated like global variable.


2. Individual copy is made for all the objects for static members.
3. All objects share same variable or same block if it is static.
4. While maintaining static variables no any effect of number of objects.
5. Static members (data) are by default initialized with zero (0).
6. Memory allocated before creation of any object is created.
7. Static members do not require any object.
8. Static members can be easily accessed without object.
9. Static variables define outside of a class always and inside also.
Outside for:- Memory allocation because no relate with objects.
Inside for:- Relate with class.

Outside Definition
Also called “Global Definition” with class name static can be accessed without
object. So from where it will get memory because without object any members cannot
get memory.
This global definition will allocate the memory for static member without object. “It
breaks the Rule of Encapsulation”

26
Outside definition syntax:-
data type class name : : (variable name);
int demo : : c;

Also called Static declaration.


Inside Definition
As per rule of Encapsulation all class members must be declared within a class so
static is also a member of a class so it also defined within a class.

10. Static members may be “private” or “public”


11. Static members can be easily accessed by object or may not by object.
12. Accessing of static members also possible without object, easily with the name of class
and SRO (::) they can be accessed.
13. Any object can easily manipulate static member variable because global can be accessed
by any one.
14. If any object change static member variable then it will affect the other object also
because these members are shared by all objects.
15. It basically used to keep the number of object that is exists in current context.
16. Life time of static members is entire program.
17. Also called “Class Variables”.
18. Static members can be initialized. If they define as constant with constant key words [ansi
c++]
static constant int a = 10; [in the class]
19. Static key word is used to define either static member variable or static member function.
20. Static variable cannot defined with in a local class.

Static Member Function:-


 As we said that static member can be either public or private.
 If they are public then they can be easily accessed outside of a class means in
main ( )

But if they are private then how these values can be accessed.
Answer is: by function
To access only these values function can be used.
But it must be a static member function because if it is a non- static then its calling
always requires object but we said that static always accessed without object thus functions which
contain static members variable they also must be static.

Definition:-
Functions which are used only for static members or which manipulate or contain only
static members are called Static Functions.
Functions with static key words is static function
Some characteristics of static function
1. They are also common for all objects of a class.
2. They are define with static key word.
3. They can be called:
a. by itself
b. With class name and SRO (::)
4. They always refer to other static members of a class “if not call by object” or “call by
class name”
27
5. They can be defining in local classes.
6. No need to define them outside of class as static member variables.
7. A class can contain no. of static members.
8. Their memory is allocated before object creation.
9. There is no any static and non- static version of same functions.
10. Any normal member function can access both non static and static members. But static
member function always access only static member variable [because not call by object]
11. These functions cannot be a “Virtual”.
12. These functions cannot be declared as const or volatile.
13. These functions do not have this pointer (because of no object).

Example of static member:-


Syntax

static return type <function name> (argument)


{
Body of function
}

Consider following example:-

class demo
{
int a;
int b;
public:
void input( )
{
cout <<” \n enter value of a”;
cin >>a;
cout <<” \n enter value of b”;
cin>>b;
}
void display ( )
{
cout<<”\n \t value of a”<<a;
cout <<”\n \t value of b”<<b;
}
};
void main ()
{
demo d1, d2, d3;
clrscr();
d1. input();
d2. input ();
d3. input();
clrscr();
cout <<”\n value of all object”;
d1. display();
cout<<”\n \n value of d2 object”;
d2. display ();
cout<<”\n \n values of d3 object”;
d3. display();
getch();
}

28
Output:- “Arbitrary”

enter value of a = 10
enter value of b =20 > d1 object value
enter value of a = 100
enter value of b = 200 > d2 object value
enter value of a = 1000
enter value of b= 2000 > d3 object value

“clean screen ”
value of d1 object ;
value of a = 10
value of b= 20
value of d2 object
value of a = 100
value of b = 200
value of d3 object
value of a 1000
value of b = 2000

 Here no any member is static that‟s why every object has different - different values and
memory.
Same program with one (b) static member:
class demo
{
int a;
static int b;
public :
void input ()
{
cout <<”\n enter value of a”;
cin>>a;
cout<<”\n enter value of b”;
cin>>b;
}
void display()
{
cout<<”\n \t value of a” <<a;
cout<<”\n \t value of b”<<b;
}
};
int demo : : b; // static or global declaration.

void main ()
{
demo d1, d2, d3;
clrscr();
cout <<\n enter values for d1 object;
d1. input();
cout <<”\n enter values for d2 object”;
d3. input ();
clrscr();
cout<<”\n value of d1 object”;

29
d1 . display ();
cout<<”\n \t of d2 object”;
d2 . display();
cout <<”\n \t value of d3 object ”;
d3. display ();
getch();
}

Out put
Enter values for d1 object
Enter value of a =10
Enter value of b = 20
Enter value of d2 object:
Enter value of a = 100
Enter value of b = 200
Enter value for d3 object:
Enter value of a = 1000
Enter value of b = 2000

“Clear screen”

Value of d1 object
Value of a = 10
Value of b = 2000

Values of d2 object.
Value of a = 100
Value of b = 2000

Values of d3 object
Value of a = 1000
Value of b = 2000

Here all b has some value which is of d3 because b is a static member and as we say that it is
common for all
d1 = b (20) is overwrite by d2 = b (200)
d2 = b (200) is overwrite by d3 = b (200)

It has proved that


> Static are common for all object of a class
> Any object change the static all will after
Here b is common for all then why b is displayed with all other a and print one time.
 B is common for all then why called with object.
 Memory is allocated without object so how we can get this value.

Ans: By “Static Function” [new version of previous program]

class demo
{
int a;
static int b;
public :

30
void input ()
{
cout <<”\n \t enter value of a”;
cin>>a;
cout<<”\n \t enter value of b”;
cin >>b;
}
void display()
{
cout<<”\n\t value of a is ”<<a;
}
static void displayb()
{
cout<<”\n \t” value of static b is “ <<b;
}
};
int demo : : b; // global declaration

void main ()
{
clrscr();
demo : : displayb();
demo d1, d2, d3;
d1. input();
d2. input();
d3. input ();
clrscr();
cout<<”\n value of all object”;
d1. display();
cout<<”\n values of d2 object”;
d2. display();
cout<<”\n values of d3 object ”
d3 . display();
cout<<”\n \t value of b by calling static function with class name”;
demo :: display b();
d1. display b();
getch();
}

value of static b is 0

enter value of a 10
Enter value of b 20

Enter value of a 100


Enter value of b 200

Enter value of a 1000


Enter value of b 2000

“Clear screen”
Value of d1 object
Value of a 10

Value of d2 object

31
Value of a 100
Value of d3 object
Value of a 1000

Value of b by calling static function with class name

Value of static b is 2000

Above program explanation:-


 Static function can be accessed anywhere.
 Static functions either can be called without object.
 Static are common for all objects.
 Static cannot access non static member.

For e.g.> if we write display - b as follows

Static void displayb ()


{
cout<<”\n value of a “<<a;
cout<<”\n value of static b is ”<, b;
}

Case 1: error will occur


Because when this function called with class name then who is owner of a error
occur.

Case 2: run successfully


Because when this function called with object either d1, d2, d3 than b is common
for all but a will print corresponding to object.

Function Overloading or Early Data Binding also called Static Data binding or Compile
Time Polymorphism.

 OOP programming has a special concept that is polymorphism.


 Polymorphism refers to “single interface multiple tasks” (SIND).
 In our programming, if we want to implemented polymorphism, then concept of
function overloading is used.

Definition
“Multiple same name functions within a same class but differ by number of
arguments or type of argument” refers to function overloading.
 Means a class can have multiple functions with same name but their argument must
differ or in number or types of arguments.
 Ambiguity also must not be there. Ambiguity refers to confliction in argument.

32
If a function contains int argument and float argument then ambiguity will occur.
To remove these problems F must be used with float parameters L must be used with long
parameters.
class demo
{
public:
int sum (int x, inty)
{
return (x+y);
}
int sum (int x, int y, int z)
{
return (x+y+z);
}
float sum (float x, float y )
{
return (x+y);
}
float sum (int x, float y)
{
return (x+y);
}
};
void main ()
{
clrscr();
demo d;
cout <<endl <<d. sum (50.96f, 98.42);
cout<<endl<<d. sum(50, 90);
cout<<endl<<d. sum(95,78.32f);
cout<<endl<<d . sum (10, 20,30);
getch()
}

In previous program, all functions have same name but they have called easily because
they have difference in either type or number of Arguments, this is not possible in C, this is
Function Overloading.

Friend Function:-
 A class has number of functions. These are called class member functions.
 Sometime two classes want to share any common functioning or it may be required that
we want to manipulate the object of two classes of different types.
This task cannot be possible with the help of member function because one class
member function cannot access the private member of another class, so generally member
function cannot do so,
Here at this point any third party function is required which can access the
private members of classes so that different types of classes can be communicate with
each other.
These types of members of our programming are called friend.
So here we will use concept of friend function.
Friend function is a special functions which define outside of a class and not
related or member of a class but it can access private members of a class outside of members.

33
 Suppose there are two classes demo 1, demo 2, and we want to get the sum of values of
(member) of these class is another object either in demo 1, or demo2.
 So here we used concept of friend function to get values of both types of objects.
 Friend function must be declared with in the class with friend keyword whose variable
we want to get.
 After declaration this function must be defined outside of class always.

Friend function can access private member of a class but object of a class must
be in function as a parameter.
Friend function is not a member of any class that‟s why no any object can call it. They
are always called without object.

Consider following example


class demo 2; // forward declaration or forward reference
class demo 1
{
int a, b;
public:
void input ()
{
cout<<”\n enter first values”;
cin>>a;
cout<<”\n enter second values”;
cin>>b;
}
void display()
{
cout<<”\n first values is ”<<a;
cout<<”\n second values is ”<<b;
}
friend demo 1 sum (demo1, demo2);
};
class demo 2
{
int x, y;
public:
void input ()
{
cout<<”\n enter first values ”;
cin<<x;‟
cout<><\n enter second values “;
cin >>y;
}
void display()
{
cout<<”\n first values is ”<<x;
cout<<”\n second values is ”<<y;
}
friend demo 1 sum (demo1 , demo2 );
};

34
demo 1 sum (demo1 p, demo2 q);
{
demo 1 z;
z.a = p.a+q.a;
z.b = p.b+q.y;
return z;
}
void main ()
{
clrscr();
demo d1, d3;
demo d2 ;
cout<<”\n enter values for first object”;
d1. input();
cout<<”\n enter values for second object”;
d2. input();
clrscr();
d3 = sum (d1, d2);  no object is required for calling sum function.
cout<<”\n values of first object”;
d1. display();
cout <<”\n values of second object”;
d2. display();
cout<<”\n values of third (added) object”;
d3. display ( );
getch();
}
out put
enter values for first object
enter first values 10
enter second values 20
enter values for second object
enter first values 100
enter second values 200
after clear screen :
values of first object
first value is : 10
second values is 20
values of second object
first values is 100
second values is 200
Values of final (added) object:
first values is 110
Second values is 220

Above program description:

 Here we create two classes, demo 1 and demo 2.


 demo 1 has a and b & demo 2 has x and y.
 Both classes has their own input ( ) and display ( ) functions (may be same name).
 Both classes have one friend function named sum.

35
 class demo 1„s friend has demo 2 as an argument, so for compilation this class contain
forward declaration to indicate the existence of demo 2 class.
 Now finally friend function is defined, which is taking two object p & q of demo1 and
demo2 respectively.
 Now this function is returning demo 1 type object, may be demo2 also.
 In main ( ) function two object d1 and d2 are created.
 d3 is also created for storing some values.
 Both functions is returning demo 1 types object so both return types is demo 1.
 Now after inputting values in d1 and d2 by their functions friend function is called.
 Friend function takes d1 and d2 in p & q and return z that is stored with in d3.
 Friend function is not a member of any class that‟s why it is always called without any
object.
 A function can be a friend of many classes.

Some characteristics about friend functions:


1. Friend keyword is used for declaring friend function within a class.
2. Friend keyword cannot be used while defining it.
3. Friend function is always defined outside of any class.
4. There is no need to define or create a friend function for a single class.
5. Friend function can be defined in a class if there is a single class.
6. Friend function can access private member of a class.
7. Friend function use private members but with object of a class.
8. Friend function always calls without any object.
9. Friend functions are also useful in operator overloading.
10. Friend function can be defined either in private or public function (no matter)
11. Generally it contains objects of classes as a Argument.
12. Friend function breaks encapsulation (drawback).
13. Friend function has no object dependency.
14. Friend function cannot have scope resolution operator.
15. Derived cannot inherit friend functions.
16. Friend functions cannot have storage classes.

Friend Class:-
 Similar to friend function there is also a concept of friend class.
 Suppose any class want to access the private members of another class then they cannot
be accessed because class cannot give its private members to anyone.
 But if we want that any class should use private member of another class then classes
which allows their private to another classes are called friend classes.
 Any friend class allows its private members to its related class.
 As in previous example, if demo2 want to access the private member of demo1 class in
its any function then demo1 has to be a friend of demo2, then easily demo2 can use
private member of demo1.
(but) demo1 cannot use private member of demo2, so vice versa this relationship cannot
exist. If two classes are friend classes of each other then such type of relation can exist.
Consider following example,
class demo1
{
int a, b;
public:
void input {
cout<<”\n enter values of a”;

36
cin>>a;
cout<<”\n enter value of b”;
cin>>b;
}
void display()
{
cout<<”\n value of a”<<a;
cout<<”\n value of b”<<b;
}
friend class demo2;
};
class demo2
{
int x,y;
public:
void input()
{
cout<<”\n enter value of x”;
cin>>x;
cout<<”\n enter values of y”;
cin>>y;
}
void display()
{
cout<<”\n value of x”<<x;
cout<<”\n value of y”<<y;
}
demo1 sum (demo 1p)
{
demo z;
z.a = p.a+ x;
z.b= p.b+y;
return z;
}
};
void main()
{
demo d1,d3;
demo d2;
clrscr();
cout<<”\n enter value for first object”;
d1. input();
cout<<”\n enter values for second ”;
d2. input();
d3 = d2.sum(d1)
clrscr();
cout<<”\n value of first object”;
d1. display();
cout<<”\n value of second object”;
d2. display ();
cout<<”\n value of final object”;
d3. display();
getch();
}
 Now in this way friend class can be used to get the private member of a class in another
class.
 Here demo2 access all the members of demo1 class even they are private.
37
 But demo1 cannot access private members of demo2 class.
 We can also create only same members of a class as a friend of other class.
 Means when only specific members functions of one class should be friend function of
another class, it must be specified explicitly using the scope resolution operator.

For eg.
Imp
[Friend demo 2: : display(demo1);]
When we write this line in our demo 1 class then demo 2 will become friend of demo 1
but only display( ) function of demo 2 class can access private member of demo 1 class.
 Means entire demo 2 class members cannot access all the private member of demo 1
class.
 By using this technique we can increase security to our data members of demo 1 class.
 Friend classes are seldom used.

Local Class:-
 Local class, a class which is defined with in any function or block is called local class.
If classes are defined with in particular block they become local.
Then these local classes can be used with in only that block or function.

For eg.

class demo 1
{

};
void test ( )
{
class demo2
{

};
};

Here demo1 is a global class where as demo 2 is a local class because it is defined
inside test name function but demo1 is global.

Some points about local classes

1. Local classes can use global variables.


2. Local classes can use static variables declared inside the function.
3. Local classes cannot use the local variables of a function in which it is defined.
4. Global variables are accessed with help of SRO (::)
5. Local classes cannot have static data members.
6. Local classes‟ members‟ functions cannot be defined outside of a class by SRO, because a
function does not contain definition of another function.
7. When a class is defined within another class is also local class and same rules are applied.
8. There is no need to define local classes with in function, but local classes can define
everywhere within the block like in function or while/ for loop or any block.

38
Types of Nested classes:-
1. Static nested class
2. Non static nested class

1. Static Nested Class:-


 Created with “static” key words
static class demo1
{

};

 A static class class can access the member of a class in which it is defined only
through objects.
 Means static nested class con not access the members of outer class directly.
Always object is required.

2. Non Static Nested Class:-

 Without static keywords is used.


 A non static nested class can easily access all the members of class in which they are
defined without defining object.

 So this type of class are beneficial while concept of nesting is used, because no need to
create the object of that class.

Constructor
We create an object of a class. It may contain data member and member function
together. If we use this object then its member variables will contain garbage value.
So the question is here how we can initialize them?
 Values can be given after object creates with dot operator but members are not
accessible outside.
 Either we can initialize the members with in a class but it is not possible, because
initialization of member is not allowed with in a class because class has no memory.
 Or another method is, create a members function of class which initialize them just like
init( )
o If a programmer can use this method then he has to remember the name of this
function, but problem cannot be solved by this method. Because any type of
functioning can be called before this init function calling.
 So what will happen?
o It is preferred that when object create at the same time. Values must be assigned
to the members of a class. During this operation, nothing can be performed.

That‟s why at this moment, a functioning (function) is require that invokes (call)
automatically and initialize class members with legal or user given values.
So that task is performed by a special function that is CONSTRUCTOR.
 Constructor is a member function of a class that is used to initialize the data member of a
class.
 It is also used to allocate the memory for the class data member.

39
 Generally it should declare within the public section.
 Its name must be exact similar to the name of the class.
 It can‟t return any type of value even not void also but it always return an Instance of
class.
 It automatically invoke when object created any where
 Parameters can be passed.
For e.g.
class demo
{
int a, b;
public :
void display()
{
cout <<endl<<”value of a”<<a;
cout <<endl<<”value of b”<<b;
}
};

void main()
{
demo d;
clrscr();
display();
getch();
}
output is :
value of a = -5732 garbage value
value of b = -23567 (vary for system)

Same with help of constructer


class demo
{
int a,b;
public:
demo() // constructor definition
{
a = 0;
b = 0;
}
void display()
{
cout<<endl<<”value of a”<<a;
cout<<endl<<”value of b”<<b;
}
};
void main ()
{
demo d;
clrscr();
display();
getch();
}
Output :
value of a 0
Value of b 0

40
Here when d object is created then constructor is called and constructor
assigning 0 to a and 0 to b so both member are initialized.
 Constructor is also a function of a class that‟s why operation or functioning can be
performed by this constructor.
 Here we can specify any type if integer value to a & b such as.
demo ()
{
a = 10;
b = 20;
}
 Here name of constructor is exactly similar to the name of class.

Definition:-
Constructor is a special function of a class, which is used for allocating the
memory for data members and initializing the data members of a class.

Declaration:-
Constructor can be defined with in a class or outside of class / with scope
resolution operations as an inline or outline function. Constructors are always Inline function
even if they are inside of class or outside of class.
 Constructor inside the class:
class demo
{
int a, b;
public :
demo()
{
a = 10; b = 20;
cout <<endl<<”inline constructor”;
}
};

Constructor define outside of class:


class demo
{
int a, b;
public:
demo();
};
demo:: demo()
{
a = 10;
b = 20;
cout<<endl<< “out line constructor ”;
}

Constructor must be define in public section of a class,


(Why)?
Constructor invokes automatically when object is created.
Object can be created, everywhere in the program but some points should be considered
while doing so.

41
Constructor can also define with in private section also but some restrictions are
here:
 Object cannot be created at anywhere.
 Object can be created only within the member function.
 Object can be created only within friend function.
 Object cannot be created in non- member function like main(), if we cannot create
object in main( ) then what is a use of it.
 But we want to create object only in member function. As a conclusion, constructor
should be defined with in public section so that its object can be created any where in
the program.
E.g.
class demo
{
demo ()
{
cout<<”constructor called”;
}
void sum() // valid
{
demo d; // member function can easily
} // call private members
friend void test ();
};
void test()
{
demo d; // valid because test is a
} // friend of a class
void main()
{
demo d; // not accessible error
}

Default Constructor
As we know that constructor can have argument, means constructor can
take the number of different – different types of arguments.
When constructor does not have any argument means numbers of argument are
zero then this type of constructor are known as default constructor.
 Constructor without argument is called as default constructor.

Ques: If we say that constructor allocates the memory for data members then is it
possible to declare object without constructor?
Ans: Yes, any program can be easily written without constructor and execute this
program successful also.

When programmer does not define any constructor within a class then compiler
creates its own constructor internally which is hidden from the programmer. This
constructor will allocate the required amount of memory if programmer does not specify his
own.
This in built constructor is known as “default constructor”. Compiler
always creates this default constructor in absence of user constructor.
 Inbuilt default constructor does not have any type of coding, it is empty, only used
for allocating memory for data members.

42
When any object is created within the memory, constructor will invoke, even if
we create the array of object with n subscript then n time constructor will call.

Parameterized Constructor
As we know that constructor that does not take argument is called as default
constructor.
A constructor can also take argument or parameter; these types of
constructors are known as parameterized constructor.
These parameters are passed to constructor during object declarations.
 Any type value can be passed to the constructor as parameters just like all system
data type or class type object also
For e.g.
class demo
{
int a;
char b;
float c;
public:
demo (int x, char y, floatz)
{
a = x;
b = y;
c = z;
}
void display ()
{
cout<<”value of integer”<<a;
cout<<”\n value of character ”<<b;
cout <<”\n value of float”<<c;
}
};
void main ()
{
demo d(10, a, 98.63); // call to parameterized constructor
clrscr();
display ();
getch();
}

output :
value of integer - 10
value of character a;
value of float - 98.63

In previous example if main contains an object without any argument then which type of
constructor will be called.
Like this
void main()
{
demo d1;
demo d2;(10, A, 98.63); > parameterized constructor
clrscr();
d1. display();
d2. display();
getch();

43
}

 Here parameterized constructor is defined with in the class but default is not defined
 In such class either the default constructor will be called or not
Obviously default constructor will be called because it is in built (but
error will occur).
Why?
When programmer define any constructor then in built constructor become hide,
it cannot be called in any case when programmer has defined any type of constructor.
As a conclusion default constructor is called only when programmer does not
define any type of constructor and if any type of constructor is defined then default cannot be
called. So in above program default constructor must be defined for d1 object.

Multiple Constructors in a Class

“CONSTRUCTOR OVERLOADING”

Ques: Is it possible to define more than one constructor with in a class?


Ans: Yes it is possible to define multiple constructors within a same class.
Some time it may be required to pass different - different values during multiple
object creation of same type. It is possible by declaring multiple constructors within a class.
 When multiple constructors are defined within the same class this concept is known as
constructor overloading.
 When multiple constructor are defined then how it can identified that which one will
execute or how they will differentiate with each other during called by object.
 While declaring multiple constructors at least one difference must be there, either in
number of argument or type of argument.
On the basis of these two concepts these constructors establish difference among
them.
 If we overload the constructor, different types of values also assign to variable along with
different type of functioning can also be performed.

E.g.
For emplaning concept of constructor overloading:
class demo
{
int a,b;
float c;
char p, q;
public:
demo (int x, int y)
{
a = x;
b = y;
cout<<”\n int – int constructor called”;
}
demo(int x, char y, float f)
{
a = x;
p = y;
c = f;
cout<<”\n int - char – float constructor called”;
}

44
demo(int x, int y, charz, floati)
{
a = x;
b = y;
p = z;
c = I;
cout<<”\n int – int char – float constructor called”;
}
demo (int x, float y)
{
a = x;
b = y;
cout<<”\n float constructor called”;
demo()
{
cout<<”\n default constructor called”;
}
};
void main()
{
demod1;
demo d2(10, 20);
demo d3(76, 98.724f);
demo d4 (10, 20, A, 68.62);
demo d5(100, A, 68.62);
demo d6(400, 500);
getch();
}

Output of above program:


default constructor called
Int – int constructor called
int – float constructor called
int- int-char- float constructor called
int – int constructor called (again called)

demo d3 (76, 98 .784f);

Why this f is used?


F make 98.724 as float because if f is not used then ambiguity will occur [explain next]
Ambiguity in Constructor Overloading:-
 Some points must be considered while implementing the constructor overloading
 Ambiguity must not be there.

Examine following condition:


#include<iostream.h>
class demo
{
public:
demo (int x, inty)
{
cout<<”\n integer constructor called”;
}
demo (int x, char y)
{

45
cout<<”\n integer – char constructor called”;
}
demo (int x float y)
{
cout<<”\n int – float constructors called”;
}
demo(float x, inty)
{
cout<<”\n float - int constructors called” ;
}
demo(float x, float y)
{
cout <<”\nfloat- float constructor called”;
}
};
void main ()
{
clrscr();
demo d1 (100, 200);
demo d2 (100, A);
demo d3 (100, 200.34);
demod4 (200.34, 100);
demo d5 (100.32, 200.34);
getch();
}
Aas rule output:
integer constructor called
int- char constructor called // this is wrong
int- float constructors called
float – int constructors called
float - float constructors called

Why? Error

ERROR 1: AMBIGUITY BETWEEN demo:: demo (int, int) and


demo:: demo (int, char)
ERROR 2: AMBIGUITY BETWEEN demo :: demo (int, int) and
demo :: demo (float, int)
EEROR 3: AMBIGUITY BETWEEN demo:: demo(int, int)
demo:: demo (int, char)
These types of error are ambiguity error; because ambiguity overloading

Ques: What is Ambiguity Error?


Ans: When same or equal entity occurs, but require one or call one then which one will
occur, that is ambiguity error.
Suppose
Teacher call Ram name student from class but class contains two Ram name student
then who will go to teacher.
 That confusion is known as Ambiguity.
 In our previous program these is also ambiguity.
 Here int can take float as an argument but decimal part will be terminated.
 Because float is actually combination of two integers x-y, x can easily be accepted by int
and float is also here.

46
Both are ready to accept these passed values and both will create ambiguity.
 Three errors will occur because these all conflicting with each other.
int, float
float, int
float, float
int, int

 So here we have to differentiate int and float.


 So this difference can be established by using their format reserved character f with float.
 So by using this f\F in it int user suppose n because this values will treat as
completely float.
 So no ambiguity will occur here.
 Our void main () function written like this:

void main ()
{
clrscr ();
demo d1 (100, 200);
demo d2(100, „A‟);
demo d3 (100, 200.34f);
demo d4(200.34f,100);
demo d5(100.32f,200.34f);
getch ();
}

Now our program is completely error free.


Now output will be as required:
Integer constructor called
int-char constructor called
int- float constructor called
float – int constructor called
float - float constructors called
 So while implementing overloading concept number of argument, type of argument
along with it, ambiguity of types should also be considered (function overloading
constructors over loading)

Dynamic Initialization of Objects


 Objects can also be initialized dynamically.
 Initial value for an object may also be given at run time.
 Means rather than passing values directly to the object in constructor, here we pass
variable instead of values.
 And values in these variables are input by user (run time )
 In this way any object may be initialized at run time.
 It is also called runtime initialization of an object.
 It is preferred when we want to initialized the object with those values which are inputted
by the user,
Means on the choice of user, object is initialized.

47
For example >
#include<stdio.h>
#include<conio.h>
class demo
{
int a, b;
public:
demo()
{
a=0; b=0;
cout<<”default constructor” ;
demo (int x, inty)
{
a=x;
b=y;
}
void display()
{
cout<<”\n value of a is ”<<a;
cout<<”\n value of b is”<<b;
}
};
void main()
{
demod1;
demod2(10, 20);
int p, q;
cout<<”\n enter any two values ”;
cin>>p>>q;
demo d3 (p,q);  (Dynamic Initialization)
clrscr();
d1. display();
d2. display();
d3. display();
getch();
}
Output above program :=>
Value of a is :=0
Value of b is =0
Value of a is =10
Value of b is = 20

Value of a is =100 User will enter in p & q and then this p & Q assigned to class
Value of b is = 200 using parameterized constructor

Dynamic Constructor:-

 The constructor can also be used for allocating the memory while creating object.
 So as per requirement different–different amount of memory can be allocated for
objects.
 When memory is allocated explicitly at the time of its construction (in constructor) is
called “Dynamic Constructor”
 When objects are of different-different size then this concept is used.
 Saving of memory.

48
 Here for memory allocation [new] operator is used.
For example:
Suppose we have three objects and in one object, we want to store 5 values, 10
values and 20 values respectively in three objects, two techniques are there:
1. Class contain array of 20 values but suitable for third one object but in another two
object memory become wasted.
2. Concept of dynamic constructor:
 Here class contains a pointer
 When object is created, required memory will be allocated as required.

Example:
class demo ()
{
int *a;
int n;
public:
demo(int x)
{
n=x;
a = new int [n];
}
void input ()
{
int i;
for (i= 0; i<n; i++ )
{
cout<<endl<<”enter value”;
cin>>a[i];
}
}
void display()
{
int i;
for(i = 0; i<n; i++)
{
cout<<”endl<<a[i];}}};
void main()
{ d1n a
demo d1 (5); 5
demo d2(10);
demo d3(20); d120n a 5values
clrscr ();
d1. input();
d2.. input (); d230n a 10 values
d3. input();
clrscr(); 20 values
d1. display();
d2.display();
d3.display();
getch();
}

Here in a above program:

d1 has 5 values memory allocation

49
d2 has 10 values memory allocation
d3 has 20 values memory allocation
[saving of memory]

Constructing two-d array Using Constructor:-


In previous section we have seen that constructor can be used to allocate
memory while object creation.

 With the help of same concept we can construct two-d array.


 Pointer to a pointer is used (* *a)

Implementation:-
#include<iostream.h>
#include<conio.h>
class demo
{
int * * a;
int r,a;
public :
demo(int * int q)
{
r=x;
c=y;
a = new int *[r];
for(int i=0;i<r;i++)
a[i]= new int [c];
}

void input()
{
int i,j;
cout<<”\n enter elements in Matrix:-”;

for(i=0; i<r;i++)
{
for(j=0; j<c;j++)
{
cout<<”\n enter element”;
cin>>a[i] [j];
}
}
}
void display()
{
int i, j;
cout<<”\n Matrix elements are:\n”;
for(i=0; i<r; i++)
{
for(j=0; j<c; j++)

50
{
cout<<”\t”<<a[i] [j];
}
cout<<endl;
}
}
};
void main()
{
demo d(4, 4);
clrscr();
d. input ();
d. display();
getch();
}

 After the creation of object at run time 4*4 d array will be created means 16 elements can
be stored.
 Structure:

0 1 2 3
0
1  4 x 4 = 16
 16 x 2 = 32 bytes
2
3

 d. input () will ask the element from user

0 1 2 3
Pointer a[0] -> 0
Pointer a[1] -> 1
Pointer a[2] -> 2
Pointer a[3] -> 3

 d. display() will display these all element in matrix form:

10 20 30 40
50 60 70 80
40 45 85 75
55 65 25 35

 In this way constructor is used to allocate memory at run time


{1d array 2d array n-d array]

51
“CONSTRUCTOR WITH DEAFULT ARGUMENT”
 Default argument refers to optional arguments means it is arbitrary that value can be
given or not.
 When we use the concept of parameterized constructor, then here during object creation
we have to pass equal number of argument as in constructor.
 Now it become optional, suppose we don‟t always pass all the arguments, as required no
of argument should be passed, and remaining arguments should be initialized with
default values:
 Means, if user does not gives values to the arguments then default values will be
initialized to object members.
 If user gives values to argument during definition then given values will passed to object
member and default values will be ignored.
 This concept is useful when passed values quantity is not fixed.
 These parameters passed from [right to left] in constructor default values.

E.g. constructor with default argument:


#include<iostream.h>
#include<conio.h>
class demo
{
int a,b;
float p,q;
char ch;
public:
demo (int x = 10, int y = 20, float i = 97.42, float j= 63.79, char t = „A‟)
{
a=x;
b=y;
p=I;
q=j;
ch=t;
cout<<”constructor called”;
cout<<”value of a” <<a;
cout<<”\nvalue of b”<<b;
cout<<”\n value of p”<<p;
cout<<”\n value of q”<<q;
}
};
voidmain()
{
clrscr();
demo d1 (100, 200, 55.70, 90.05,”p”);
demo d2(100, 200, 55.70, 90.05);
demo d3(100, 200, 55.70);
demo d4(100, 200);
demo d5 (100);
demo d6;  default constructor
getch();
}

Output will: =
value of a = 100
value of b = 200

52
value of p = 55.70
value of q = 90.05
value of ch = p
value of a = 100
value of b = 200
value of p = 55.70
value of q = 90.05
value of ch = „A‟ > default value
value of a = 100
value of b = 200
value of p = 55.70
value of q = 63.79 > default value
value of ch = A > default value
value of a = 100
value of b = 200
value of p = 97.42 > default value
value of q = 63.79 > default value
value of ch = A > default value
value of a 100
value of b = 20> default value
value of p = 97.42 > default value
value of q = 63.79 > default value
value of ch = A > default value
value of a = 10 > default value
value of b = 20> default value
value of p = 97.42 > default value
value of q = 63.79 > default value
value of ch = A > default value
Point
 Specified values are of higher priority than default values.
 These values are copied from right to left.
 No any argument must be without value between two default values, right to left value
must be given as default in sequence.
 No need that all argument must optional or default. Any number of arguments can be
default.
 A constructor within all parameters as default is treated as a default constructor so here
no need to create default destructor.
 As in above program d6 object created easily because single constructor with all
arguments as an optional is treated as a default constructor.
 Overloading of default constructor is easily possible but ambiguity must not be there.

Ques: Which one is better either Constructor overloading or Constructor with default
arguments?
Ans:
Constructor overloading is better because:-

 Default arguments might not work for all possible combinations of arguments where a
constructor may be overload for all possible combination of argument.

53
 Default arguments contain only one body so only that single definition (task) will execute
but if we want to perform different – different task with different number of values than
overloading is used.

By constructor overloading we, can secure the compiler from managing the
values to assign to their arguments directly based on no. of arguments or type of arguments
constructor called
But
With default values compiler has to manage it for different – different values at
different – different times and its appropriate argument.

 Overloading is easier than default arguments


 Makes program complex but default argument reduces the line of code.

Copy Constructor:-

 Another type of new type of constructor is copy constructor.


 A copy constructor is used or invoked whenever we want to initialize the object with the
another object of same time
 When one object is initialize with another object of same type is referred as an object
assignment.
 Whenever object assignment is performed copy constructor is called.
 We can create our copy constructor; if we have not defined any copy constructor then
compiler automatically creates it.
 A class can have only single copy constructor.
 A copy constructor takes a reference to an object of the same class as an argument.
 Copy constructor can be easily used with another different constructor like default or
parameterized.
 That is also called as explicit copy of object because
> It does manually
> We can perform some another task also during object assignment which for
example:

#include<iostream.h>
#include<conio.h>
class demo
{
int a,b;
public:
demo (int x, inty)
{
a= x;
b = y;
}
demo (demo &d)
{
a = d.a;
b = d.b;
}
void display()

54
{
cout<<”\n value of a”<<a;
cout<<”\n value of b”<<b;
}
};
void main()
{
demo d1 (10, 20);
demod2(d1);
demo d3 = d2;
clrscr();
cout<<”\n values of d1 object”;
d1.display();

Constructor calling technique


Any constructor can be called with in two ways these are:
1. Implicit call
2. Explicit call

1. Implicit call:-
It is general calling technique. When during object creation the name of
constructor is not specified, it is called automatically. This method is also called
as shorthand method because it is shorter and easy to use and look better.
demo d(10,20); > implicit call of parameterized constructor

2. Explicit call:-
In this technique the name of the constructor is explicitly provided to call it.
While creating object even the class name is here but again the name of class is used as a
constructor.
demo d = demo (10, 20);> explicit call by parameterized constructor.

Why two techniques are given?


Most probably implicit call is used. Explicit call technique is used when there is a
need of technique is used when there is a need of temporary instance or temporary object.
Some time it may be required to create a temporary object instance:
A temporary instance which exist in the temporary as long as it being used, after
that if there is no any use of them automatically they are destroyed.
A temporary instance does not have name so to create the temporary instance
explicit call of constructor are used.
For e.g.

Permanent > d1. display (10,20)


Temporary > demo (50, 60) . display();
(Instance)
Here in above statement d1 exist with 10 & 20 values and can be easily again
used or access where as demo (50, 60) .display line will create temporary instance at this time.
A temporary instance will create its values used by display () function, after that it
cannot be used and it removed by compiler automatically.
So when intermediate objects are required for some operation then this
temporary instance is used and to create this instance, explicit call of constructor is used.

55
cout <<”\n value of d2 object”;
d2. display ();
cout<<”\n value of d3 object”;
d3. display();
getch();
}
Output:
value of d1 object
value of a- 10
value of b – 20
value of d2 object
value of a – 10
value of b – 20
value of d3 object
value of a – 10
value of b – 20

Copy constructor calling technique:-

1 demo d2 (d1);
2 demo d2= d1;
3 demo d2;
4 d2 = d1;

Line 1 and line 2 are invoking copy constructor value of d1 is copied into d2 object.
Line 2, does not invoke our copy constructor, here in built technique is called that is known
as members of the constructor.

When copy constructor occurs?


1. Whenever any object is initialized by another object of same type, at this time copy
constructor is called [as specified previous program]
“In short we can say whenever the task of object assignment is performed
directly or indirectly copy constructor always invoke”

2. When an object is passed by value then also copy constructor invokes:


 The copy constructor invoked when an object is passed by value to a function as an
argument.
 The passed by value technique require a copy of passed argument that is object.
 Thus here the copy of actual argument (object) is assigned to formal argument then
at this place copy constructor invoked.

Note:-
 Copy constructor does not invoke in case of call by reference or call by pointer
method because here copy of argument is not created. Actual object is passed as an
argument.

3. When any object is returned by function then again at this time also copy constructor is
invoked.

 As we know that function can also return object and this object is assigned to
assignment object during calling of function.
 When any object is return then its copy is returned to the object.
56
 Again here copy is made and this copy will assign to another assignment object, here
constructor is invoked.

 Actually the copy constructor create a another temporary object to hold the return
value of a function returning an object
 As a conclusion we can say, when any object function return any object and copy of
this object is passed to calling assignment object then copy constructor is invoked.

Point:-
If we do not write any copy constructor for a class, the compiler creates implicitly
defined copy constructor which is inline public member of its class.
 Both points are described within next example

Why the argument a copy constructor is always passed by reference?

 Whenever we create our own copy constructor we have to always pass the object by
reference otherwise error will occur if we do not use reference variable.
 Here basically error is “out of memory” or infinite loop.
 (Why)?
 When an argument is passed by value, a copy of it is created
When copy of object is constructed then who works?
Here again copy constructor is invoked
Copy constructor creates a copy of object itself, thus it called itself.
Again the called copy constructor requires another copy so again it is called. So infact it calls
again and again, it will become infinite so compiler runs out of memory.
So, in the copy constructor the argument must be passed by reference so that to
make a copy of the passed object, original object is directly available.

For eg:
#include<iostream .h>
#include<conio.h>
class demo
{
int a, b;
public:
demo () {}
demo (demo &d)
{
a = d.a;
b= d.b;
}
void input ()
{
cout<<”\n enter first numbers”;
cin>>a;
cout<<”\n enter second value”;
cin>>b;
}
void display()
{
cout<<”\n value of a”<<a;
cout<<”\n value of b”<<b;
}

57
demo sum (demo d)
{
demo z;
z..a = a+d.a
z.b = b+d.b;
return z;
}
};
void main()
{
clrscr();
demo d1,d2,d3;
cout<<endl<<”enter value of first object”;
d1. input();
cout<<endl<<”enter values for second object”;
d2. input();
d3= d1. sum (d2);
cout<<”\n first object values are”;
d1. display ();
cout<<”\n second object are”;
d2. display();
cout<<”\n value of final object are”;
d3. display();
getch();
}

out put
enter values for first object
enter first value - 10
enter second value - 20
enter value for second object
enter first value -100
enter second value 200

first object values are


value of a -10
value of b- 20
second object values are
value of a - 100
value of b – 200
value of final object is
value of a - 110
value of b - 220

 Here both 2 & 3 points are described


 Here d2 is passed as an argument is sum function so this copy of d2 is copied into d here
copy constructor will be invoked
When d2 passed to sum then following line interpret: [demo d= d2] [internally]
Because of this line copy constructor will invoke
 Now after manipulation z will return from function and d3 will catch or accept it. So
when z will return then following line interpret [demod3 = z;] [internally]
Means copy of z will pass to d3 object so here also copy constructor will invoke

58
Order of Constructor Invocation:-
 Whenever the object is created constructor invoke automatically.
 Our program contains no. of objects so here question arises that in which order their
constructor will be invoked?
Ans:
 There is a predetermined order of constructor invocation.
 The constructor for objects is invoked in the order they are defined.

Special point:-
When classes contain the objects of another class as its members [containership].
In such cases the constructor for member objects are invoked first and then only the
constructor for the containing classes invoked.

MEMORY INITIALIZATION LIST:


“MEMBER INITIALIZATION LIST”

 As we known constructor is used to initialize the members of a class.


 Suppose a class contain constant and reference variable as a member directly, values
cannot be assigned to them because they are in class.
 For assign values to these types of variables mem- initialization list is used

For e.g.

class demo
{
int a, b;
Const int t;
public :
demo (int I, int j, int k, int l)
{
a= I;
b=j;
t=k;
p=I;
}
};
void main()
Output: {
error demo d(100, 200, 10, 50);
getch();
}

 Reference member p is not initialized so cannot modify a const object.

Reason:
 Here a and b both are normal variables, they can be directly initialized.
 But constant variable t and reference variable p cannot be initialized like this.
 To initialize t and p, mem-initialization list is use within constant.

59
 ”:” is used along with constructor first line and then this constituent data member (const,
reference) are written with their initial value.

The above program this will write like this:


class demo
{
int a,b;
const int t;
int &p;
public:
demo (int I, intj, int k, int l) : t(k),p(t)
{
A = i;
b = j;
cout<<endl<<”value of a”<<a;
cout<<endl<<”value of b”<<b;
cout<<endl<<”value of t”<<t;
court<<endl<<”value o f p”<<p;
}
};
void main()
{
demo p(10, 20, 500, 700);
getch();
}
output :
[error free program]

value of a - 10
value of b- 20
value of t-500
value of p-700

Here non constant member or non reference variable can also be initialized by mem list.
This mem list is used for constant members and for pass argument to super, parent class used
with class name.

Some Conclusion About Constructor:-


[KEY POINTS]

1. Constructor is a member function of a class.


2. It is used to allocate the memory for objects.
3. It is used to initialize the member of a class.
4. Its name is exact similar to the name of class.
5. It cannot return type of value even void also.
6. It return instance of a class but internally.
7. Multiple constructors easily declared with in a class means constructor overloading is
easily possible.
8. It invokes automatically no need to call explicitly.
9. It calls whenever objects are created.
10. Constructors can also take arguments.
11. A constructor with argument is called as Parameterized Constructor.

60
12. A constructor also has default argument.
13. A constructor without argument is called as Default Constructor.
14. If constructor is not define or created then automatically implicit default constructor is
created.
15. Constructor cannot directly initialize reference variables.
16. Constructors cannot directly initialize constant variables.
17. For initializing constructor or reference variables mem initialization list is used.
18. A copy constructor is used for object assignment.
19. Implicit copy constructors are also available if we not define our own.
20. Constructor must be defined with in public section.
21. Parameterized constructor or our any constructor hides the default (implicit) constructor.
22. Constructors can also define outside of a class with help of scope resolution operator.
23. A constructor with all argument as default is equal to default constructor.
24. Constructors can be called by two techniques.
1 Implicit call
2 Explicit call
25. Explicit call is use to create temporary instance of a class.
26. Primitive data type also has constructor.
[Compiler dependent int i(10)]
27. Constructor invoke in the order of object declaration.
28. Dynamic initialization of object is also possible by constructor.
29. Constructors cannot be inherited.
30. Constructor of derived class always called base class constructor.
31. Through base class constructor with mem list values can be passed to parent class.
32. Constructors cannot be virtual.
33. The constructor may not be static.
34. The built constructor is by default of public category.
35. It is not possible to take the address of a constructor.
36. An object of a class with a constructor cannot be members of union.
37. Member‟s functions may be called within a constructor.
38. Constructors can be placed anywhere in a class.
39. Constructors overloading is better than constructor with default arguments.
40. Constructors used to allocate memory, they make implicit calls to the operator new and
delete when memory allocation is required.

Destructor:-

 Destructor is just opposite of constructor.


 As name implies constructor is used to allocate the memory where as destructor is used
to deallocate this allocated memory.
 Destructor is also invoked automatically when object is destroyed.
 Objects destroy when program control comes out of its scope.
 Destructor syntax is same as constructor.
 Its name is also equal to name of a class.
 It cannot return any type values.
 It differentiate constructor to destructor a special symbol tilde (~) is used before name of
constructor.
Basically it is a bitwise not operator means > ~ constructor
not constructor = destructor
 It is also available by default if we do not create.
 It does not take arguments,

61
Because it is simple thing, during destruction of object what is the requirement of
parameters or arguments.
 Delete operator may be used by destructor like constructor use new.
 During constructor of an object by the constructor resources may be allocated for use to
object such as file or memory area can be allocated to it.
This resource must be deallocated before the object is destroyed
So it is our responsibility to deallocate this memory
 Where we will write the coding for deallocating resources,
This coding will written in destructor
Press alt + f5 [you cannot see destructor output]
Destructor called [for d4]
Destructor called [for d3] [prove next]
Destructor called [for d2]
Destructor called [for d1]

Why Alt +F5 pressed?


Because after getch ( ) execution destructor will call because, at point of getch( ), program
finally going to finish at this movement destructor will call so we have to press [alt +f5].
 If we do not use getch( ) then constructor & destructor both will not show us, we have
to press alt +f5
After that we will see both constructor and destructor output
 in this way destructor called.

Ques: How we can find out the sequence of constructor and destructor execution?
Ans: Follow below program:
Here we use static member variable, which is common for all the objects of a class
 At the time of constructor we will increase it by one and display it.
 At the time of destructor we will decrease it by one and display it.

The error of destructor calling is in opposite (reverse order) in which constructor invoke
For e.g.
demo d1, d2, d3, d4;
Constructor order > d1, d2, d3, d4;
Destructor order > d4, d3, d2, d1;
 Destructor cannot be inherited.
 We cannot get address of destructor.

e.g.
#include<iostream.h>
#include<conio.h>
class demo
{
static int i;
public:

demo ()
{
i++;
cout<<endl<<”constructor called for d “<<i;”;
}
~ demo ()
{

62
cout<<endl<<”destructor called for d “<<i”;
i--;
}
};
int demo : : i;
void main()
{
demo d1, d2, d3, d4;
getch();
}
Output:-
Constructor called [for d1]
Constructor called [for d2]
Constructor called [for d3]
Constructor called [for d4]

63
Inheritance

It is also called “Derivation”, implement the concept of “Reusability feature”

Suppose we have developed any code and if we require that code


again then two possibilities are here:
1. Either again recode the functionality or
2. Use this functionality again without written it again.

2nd one is better; means once implemented code should not be recode or redefine again. That
process or facility is called “inheritance”

Inheritance is one of the most important features of oops and it is most useful
one.
Inheritance refers to reusability means in oop any class can use the functionally of
another existing class.
Means suppose we have implemented a class and another new class want to use
or access the properties of previous class, it can be done by inheritance.
If two or more classes inherit then they can share their properties.
For e.g.
Children inherit properties of parents so it is the facility for children not to re-
declare the functioning of parent again in children.
So child is inherit with parent. We can also do this inheritance with in our
program.

In our programming
Once or more classes can get the properties of another class if inheritance is
there.
So when any class gives functionality or properties to another class then it
called:
BASE CLASS
PARENT CLASS
SUPER CLASS
ANCESTOR
When any class accepts or requests the properties of base / parent class then it is
called:
DERIVE CLASS
CHILD CLASS
SUB CLASS
DESCENDENT
 Inheritance implement Is-Arelationship.

Need or importance of inheritance:-


1 No need to recreate the created code again
2 Faster developments
3 Easier maintenance
4 Easy to extend
5 Transitive nature of inheritance [grand child directly access properties of
Grant parent]

64
Ideal C++

6 Code sharing at so many levels.


7 Implementation of aggregation
[Multiple classes can be combined in single one]
The technique of building new classes from existing class is called “inheritance”.

Various types of inheritance:-

There are different types of Inheritance as per requirement it is used.


1 Single inheritance
2 Multiple inheritances
3 Multilevel inheritances
4 Hierarchical inheritances
5 Hybrid inheritances
6 Multipath inheritances

1. Single Inheritance:-
In this inheritance only two classes are involved one parent class and another one
is child class.

A Parent class

Child class
B

Here b class inheriting the properties of parent class.

2. Multilevel Inheritance:-
In this inheritance, it is expansion of single inheritance, here multilevel
classes are involved but in levels and every class involved at same level.

Agrant parent
|
|
parent
B |
|
child
Here C is inheriti C class.
B inheriting classes
Implement “transitivity” nature.
3. Multiple Inheritance:-
 It is one of the most useful and practical oriented type of inheritance
 This inheritance implements the concept of aggregation.
Means here multiple classes combined into single one class.
 Multiple parent classes exist.
 One child class
A B

Base class [a] [b] base class 2


C

- 65 -
Ideal C++

[c]
Child class [“c” child inheriting properties of both parent classes 1 & 2]

4. Hierarchical Inheritance:-
When many sub classes inherit from a single base class, it is called hierarchical
inheritance.
A

B C

B inheriting properties of c also inheriting


5. Hybrid Inheritance:-
 Hybrid inheritance is a combination of other inheritances
Means when two or more types of inheritance involving inheritance is called
hybrid inheritance.
 It contain classes in random or arbitrary manner so different types of structure can be
here some are:

A A B C
B D

D E

E F G

6. Multipath Inheritance:-
[Special case of hybrid] It is one of the critical types of inheritance here contain
following classes:
 Grand parent classes
 Parent class
 Child class
 Means when multiple paths exist between any two classes it is called multipath
inheritance.
A

B
C C

[B inheriting property of A , C inheriting property of A, d inheriting property of both B & c.]

 
- 66 -
Ideal C++

Visibility Mode (VM):-


“Access control in inheritance”
 Visibility mode is one of the most important concepts in inheritance and it is must in
implementing the inheritance.
 V.M. visibility mode controls the visibility and availability of inherited base class
members in the derived class.
 VM specify the various availability of restriction on the members of its parent class.
 When parent gives the properties to its child, the VM specify the rules accessing or
availability of member of parent in child class.
 Whenever we inherit the classes then VM must be there (use in syntax) if not by default
it is private.

We can say that VM specify the privileges for child class to use the member of parent class.
 These VM are similar to the access specifiers, they are used for same class member to
specify their privileges to outside
 But VM are used for specify the privileges for using the members of parent with in child
classes.
Syntax :=>
class <derive class> : VM <base class>
{
};

Types of visibility mode:-


1 Public
2 Private
3 Protected.

Public Mode:-
 When public VM is used then all the protected and private member of classes can be
easily accessible in derive class.
 Means when you want to use all the protected and public members of parent class in
derive class the public VM is used.
 These inherited (public) members can also again pass to their derive class , child class.
 With publicly derived class the public members of the base class become the public
members of the derived class.
 With publicly derived class the protected members of the base class again become the
protected members of the derived class.
Or we can say the public VM does not change the access specifies for
inherited members in the derived class.

Eg
class base
{
private: // by default
int a;
void input ( );
protected:
int b;
void sum ( );
public:
int c;

 
- 67 -
Ideal C++

void display();
};
class derive : public base
{ here
a cannot inherited by derived
void input( ) also
[because private cannot inherited]
b will become protected member of this class
void sum ( ) also
[because priority of protected is higher than public]
c will become public member of this class
void display ( ) also
};

 Here all the access specifiers are not changed for all parent class members in derive /
child class.

2. Protected Visibility Mode:-


 When protected VM is used then
Private is not accessible
[Private cannot be inherited]
 Protected members of base class become protected again in derive class.
 Public members of base class become protected in derive class.
 Means all public members of base will become protected in derive class.
Eg
class super
{
int a;
protected :
int b;
public :
int c;
};
class derive : protected super
{
here :
a cannot inherited
b& c wil become protected here
};

3. Private Visibility Mode:- (it is by default visibility mode)


 When private VM is used then all public and protected members of base class can
easily be accessible.
 Private VM makes all the members of public class as private in derive class.
 When derive class takes all member of base class as private then this can again
cannot give or pass it to any another class even not to child also.
 It is used when child class does not give its parent „s class members to other (child ,
class )
eg class super
{
int a;
protected :
int b;
public :

 
- 68 -
Ideal C++

int c;
};
class derive : private super
{
Here a cannot inherited
b & c will become private members of this derive class and they again cannot give to its child
;
};

Table which show VM role inheritance

BASE CLASS DERIVE CLASS


ACCESS PRIVATE PROTECTED PUBLIC
SPECIFIERS
PRIVATE NON INHERITED NO INHERITED NO
PROTECTED PRIVATE PROTECTED PROTECTED
PUBLIC PRIVATE PROTECTED PUBLIC
Short cut to learn above table:-
Learn following sequence

Private
|
Protected
|
public

 Take any two mode above this :


Mode which comes first in above level, will become final (answer) mode for
members of parent class in child class private cannot be inherited.

For eg:
Public & protected : protected
Private & public : no inheritance
Public & public : public | prior in above table
Protected & private : private |

Rules for accessibility of members of base class

Base class Accessible from Accessible from Accessible from


Access Specifiers Own class Derived class objects outside class
Public Yes Yes Yes
Protected Yes Yes No
Private Yes No No

 So we should consider both


o base class specifiers
o visibility modes, during inheritance

 
- 69 -
Ideal C++

Final conclusion:-
i. If you want that members cannot be available anywhere either in child class or outside of
classes then declare then with private.

ii. If you want that members can be accessed only within the child class not anywhere then
declare them as protected then they can be accessed by only child classes.

iii. If we want to make all the members available for every where either in child classes or
outside with object declare them with public.

* A special POINT TO BE NOTED if we check the memory size of child class object then total
memory is calculated. Means child class and parent class both members are allocated and
counted even if they are private.

Generally we declare the object of last child class because it contains the function of all
the parent classes and by its object all functioning can be easily accessed (Parent + itself).
So parent class object will not create, so no need to define their constructor then
who will allocate memory for parent class members because constructor of a class allocate
memory for class members.
Finally, whenever child class object is created then automatically rather then
calling the child class constructor, the constructor of parent class is called first then child class
constructor is called.
If constructor is not defined by user then default constructor is called always.

The sequence of calling constructor is always depend on the sequence of


inheritance means always top level parent class constructor is called first then child class
constructor is called.

Example
class demo1
{
public:
demo1 ( )
{
cout<<”\n demo 1 constructor”;
}
};
class demo 2: public demo 1
{
public:
demo 2()
{
cout<<”\n demo 2 constructor”;
}
};
class demo 3 : public demo 2
{

 
- 70 -
Ideal C++
public:
demo 3
{
cout <<”\n demo 3 constructor” ;
}
};
void main()
{
clrscr();
demo3 d;
getch();
};

Output demo 3 constructor (this is wrong)

(why) ?

actual out put


demo 1 constructor
demo 2 constructor
demo 3 constructor
 Because always first parent class constructor is called then child class constructor.
 Here relationship is:
demo 1 grant parent

parent
demo 2
child
demo 3

 
- 71 -
Ideal C++

 First of all demo3 constructor is called but demo 2 is a parent of demo 3 is a parent of
demo 2 and demo1 has no any parent that‟s why
First demo1 constructor is called
Then demo2 constructor is called
Then finally demo3 constructor is called

Conclusion:-
 Constructor of parent class is always called first then child class
 In case of multiple inheritance (multiple parent) on the basic of the inheritance
relationship constructor is called

For e.g.

class demo 1
{
};
class demo 2
{
};
case 1 : class demo 3: public demo1, public demo 2
{
};
Now demo 1 constructor is called
Then demo 2 And then demo 3,
Case 2 class demo 3 : public demo 2: public demo 1
{

};
Now first demo2 constructor
Then demo1
Then demo 3 constructor is called

Argument can also be passed to parent class member through child class constructor.
 We create the object of child class so parameter will be given to child class but if these
values also required with in parent class then child class constructor can transfer required
values to parent class constructor so the members of parent class can be initialized.
 When child class constructor is defined then at this time parent class required values also
mentioned as a list separated by colon sign (:) and parent class name.
o Then these mentioned values can passed to parent class and so on.
o If a child has multiple parents then multiple parent name can be specified here.
 In this way through child class constructor values can be passed to parent class or
members of parent class initialized by child class constructor.
 Required parameterized constructor must be available with in parent class if child
sending values to parent.
E.g.
class demo 1
{int a; public:
demo (int x)
{
a = x;
cout <<”\n demo 1 value”<<a;
}

 
- 72 -
Ideal C++
};
class demo 2 public demo 1
{int b; public:
demo (int x int y) : demo 1( y)
{
b = x;
cout<<”\n demo 2 values ”<<b;
}
};
class demo 3: public demo 2
{int c; public:
demo 3 (int x, int y, intz): demo 2 (x,z)
{
c = y;
cout<<”\n demo 3 values ”<<c;
}
};
void main()
{

Output:
clrscr();
demo 3 d (10, 20, 30);
getch();
}
demo 1 value 30
demo 2 value 10
demo 3 value 20

 Multilevel inheritance is there that‟s why this sequence is generated.


 First of all demo3 constructor is called with x = 10, y = 20, z = 30 value , here
 x = 10, z = 30 passed to demo 2
 demo 2 accept this x and z in x &y (parameter name can be anything) .
 y = 30 , passed to demo 1 among x & y.
 demo 1 accept this y in x and finally assign to x
 So demo 1 value is - 30
 Then demo 2 is called
 demo 2 value is -10
 Then demo 3 is called
 demo 3 value is 20

class demo 1
{
int a;
public:
demo (int x)
{
a = x;
cout<<”\n demo 1 value ”<<a;
}
};
class demo 2
{
int b;
 
- 73 -
Ideal C++
public:
demo (int x)
{
b = x;
cout<<”\n demo 2 value ”<<b;
}
};
class demo 3: public demo 1, public demo 2
{
int c;
public :
demo3(int x, inty, intz);
demo1 (x) , demo2 (z)
{
c = y;
cout<<”\n demo 3 value”<<c;
}
};
void main()
{
clrscr();
demo 3 d(10, 20, 30);
getch():}

Here Inheritance is multiple:

demo 1 demo 2

demo 3

 demo 3 inherit both demo1 and demo 2 so demo 3 has to pass values to both demo 1
and demo 2 classes
 This line pass values to parent class
10 20 30 10 30
demo3 (int x, int y, int z) : demo1(x) , demo2 (z)
{
c = y;
}
 First of all:-
demo1 is called because it is first parent with 10 values

 Then:-
o demo 2 is called because it is second parent
 Finally:-
o demo3 constructor is called with 20 values.

 
- 74 -
Ideal C++

Output

Demo 1 values 10
Demo 2 values 20
Demo 3 values 30
 Sequence of constructor calling always depends on the inheritance relationship rather than
specified field with constructor list.
 Means if we write:
Demo3 (int x, inty, intz) : demo2 (z) demo1 (x)
{
}
Then same output will generate because constructor sequence is based on classes
relationship.
 But if we write
class demo3 : public demo2, public demo1
{}
Here in this case always demo 2 constructor is called first even specified list has different
sequence.
 Random or arbitrary values can also be passed
demo 3(int x, inty, intz): demo2 (x+50), demo 3 (y+90)
or
demo 3 (int x, int y, int z): demo 2 (100), demo3 (500)

 Same values can also be passed in all classes


class demo 1
{
int a;
public:
demo1(int x)
{
a = x;
cout<<”demo 1 values ”<<a;
}
};
class demo 2: public demo 1
{
int b;
public:
demo 2 (int x): demo 1(x)
{
b = x;
cout<<”\n demo values ”<<b;
}
}:
class demo 3 : public demo 2
{
int c;
public:
demo 3 (int x) : demo 2(x)
{
c = x;
cout<<”\n demo 3 values”<<c;
}
};

 
- 75 -
Ideal C++

void main()
{
clrscr();
demo 3 d(10);
getch();
}

Output:
demo 1 values 10
demo 2 values 10
demo 3 values 10

All classes contain same vales because same values is passed to all constructor
that is x.

 
- 76 -
Ideal C++

Member Classes: Nesting Of Classes:-

CONTAINERSHIP
 Inheritance gives us the facility of using the property of a class in another class without
redefining it.
 But sometime it can also be possible that one class can contain object of another class
and through this object another classes property can be accessed, it is called
containership or aggregation.
 It is also called nesting or containment or composition.
 So any object can be a collection of another group of objects of another classes

class demo 1
{

};
class demo 2
{

};
class demo 3
{
demo d1;
demo d2;

demo 3 contains object of demo 1 and demo 2 class that are d1 and d2 this concept is called
containership.
With the help of this d1 and d2 the property of demo1 and demo2 can be
accessed in demo 3 class.

Points:-
When a class demo 3 contain two objects d1 & d2 then which class constructor
called first.
Ans: Always member variable objects constructor (d1, d2) called first then demo 3 class
constructor is called.

E.g.
class demo 1
{
public:
demo1 ( )
{
cout<<”\n I am in demo”;
}
};
class demo 2
{

 
- 77 -
Ideal C++

public:
demo ( )
{
cout<<”\n I am demo 2”;
]
}:
class demo 3
{
demo 2 d2;
demo 1 d1;
public :
demo 3()
{
cout<<”\n I am in demo 3”;
}
};
void main()
{
clrscr();
demo 3 d;
getch();
}
output
I am in demo 2
I am in demo 1
I am in demo 3

In previous program demo 2 constructor is called first because first it will create then demo 1
and then demo3 itself constructor will called.
 So by using the concept of nesting of containership, the reusability can be
implemented.
 This type of relationship is also called as [HAS- A] relationship.

VIRTUAL BASE CLASS (VBC)


 This type of class is used when special condition occurs of multiple inheritance or
with hybrid inheritance or multipath inheritance.
 Because in such type of situations ambiguity occurs, so concept of virtual base class
is used to remove this ambiguity problem.

Condition:-
When any grant child want to access the properties of grant parent and
multiple parent is there then child will become confused from which parent, child can
access the property of grant parent.

Demo1

Demo 2 demo 3

Demo 4

Demo 2, 3 can easily access property of demo 1 because there is no ambiguity of


path between them, they can directly access the property of demo1

 
- 78 -
Ideal C++

(But)
When demo4 want to access the property of demo 1 then it will become confuse
because demo1 have two parents‟ demo2 and demo3 and both have property of demo1 so
demo 4 has ambiguity to access demo 1 property.
Demo 4 can easily access property of demo 2 and demo3 but problem will occur
in case of demo4

For removing this ambiguity VBC is used.


For removing such that type of problems two solutions are there
 Either specifies the path to demo4 that from which parent (demo 2, demo3) it can
access demo 1 property.
 Or inherit demo 1 class as virtual to demo 2 and demo3

Consider following example:


a
demo1

b demo2 demo3 c
a a
demo4
d
[b,a,c,a] > ambiguity [demo2a, demo 3a]
Here demo 4 has 2 a, one of demo 2 and one of demo3, so demo4 is
confused here so ambiguity error will occur.

Implementation:-
class demo1
{
public:
int a;
};
class demo 2: public demo 1
{
public:
int b;
};
class demo 3 : public demo 1
{
public:
int c;
};
class demo4 : public demo 2, public demo3
{
public:
int d;
};
void main( )
{
clrscr();
demo 4p;
cin>>p.d;
cin>>p.c;
cin>>p.b;
cin>>p.a; - error occur

 
- 79 -
Ideal C++

cout<<p.d;
cout<<p.c;
cout<<p.b;
cout<<p.a; error occur again
getch();
}

Solution 1:
Here a occur ambiguity because a can be accessed by two demo 2 and demo3 so
here we can specify the path.
As given below
void main ( )
{
demo 4 p;
cin>>p.d;
cin>>p.c;
cin>>p.b;
cin>>demo 2:: a;
//cin>>demo 3:: a;
cout<<p.d;
cout<<p.c;
cout<<p.b;
cout<<demo 2:: a; // cout<<demo3;;a;
getch();
}
Correct output

 By specifying the path we can remove the amibuity.


 If for input demo2 is selection , then again always same demo2 is used for getting
values.
 Means if you use demo2 for input and demo3 for output of a then garbage value will
display.

Drawback:
This solution can be used to remove ambiguity but it also does not
maintain “data abstraction” or “hiding” so solution 2 is used.

Solution 2:
 Here concept of VBC is used
 demo 4 want that when he want to access the property of demo1 then a virtual path
here should be created without interference of demo2 and demo3 classes. So no
ambiguity will occur.
 This requirement can be fulfilled by virtual base class.

Actual concept:-
The actual concept is that,
Whenever demo4 want to access properties of demo1 then only single copy of
demo 1 should be maintained among all the parents of demo4 (demo2, demo3), so because
of this no any ambiguity will occur. Here classes are not virtual but relationships is virtual
So to do so, demo2 and demo3 will virtually inherit the demo1:
class demo 1
{
public:

 
- 80 -
Ideal C++

int a;
};
class demo2 : virtual public demo1
{
public:
int b;
};
class demo 3: public virtual demo1
{
public:
int c;
};
class demo 4 public demo2, public demo3
{
public:
int d;
};
void main()
{
demo4p;
cin>>p.d;
cin>>p.c;
cin>>p.b;
cin>>p.a; no error
cout<<p.d;
cout<<p.c;
cout<<p.b;
cout<<p.a; no error
getch();
}
Here no any error will occur because demo1 has become virtual and virtual class
maintain a common copy among its children while its grant parent want to access its

a
demo1
b c
demo2 a demo3

demo4
d
Note:-
Here demo1 is a virtual base class.
Virtual word can be used either before public or after keywords.

class demo2 : virtual public demo1


{

};
or
class demo2 : public virtual demo1
{

};
Both are equal exactly

 
- 81 -
Ideal C++

 It is not possible that we make any one class as virtual, all intermediate classes must be
virtually inherited otherwise ambiguity will occur.

Conclusion:-
When ever any grand child wants to access properties of its grand parent
then if multiple intermediate parents are these then their presence will create ambiguity. So these
all intermediate classes must inherit grand parent as virtual, this is Virtual Base Class.

Abstract Classes:-

 An abstract class is a class which is not used for creating any object.
 As we know while using inheritance, we always create object of child class, because child
class has property of all parent classes.
 So there is no any need to create parent class object, it only provide base to its child class.
 It is designed to act as base class and always inherited by other class and other classes will
use this class as their base class.
Such types of classes are called Abstract Classes.
Or
Any class which contain PVF (pure virtual function) also called abstract class.
Important
 Generally abstract class always provide outline of functioning to other class which inherit
it.
 Abstract classes can be used as framework.
 This framework can be used by another class to provide bases so that new functionality
can be created with the help of this above class.
 Abstract class has no functioning, so its object or instance cannot be created.

Pointer to Object:-
As we know that any variable can also have pointer which point or hold address
of a variable, and it is a rule that type of a variable and pointer must equal or same type.
Similar to that object can also have pointer which hold the address of entire
objects.
For e.g.>
demo d;
demo*p;
P= &p;
Here p is a pointer to object this pointer p is pointing to an entire object.
For accessing the member of a class through pointer  operator is used rather than . dot
operator.
It is called pointer to member access operator.

eg.
class demo
{
int a,b,c;
public:
void input()
{
cout<<”\n enter the value of a ”;
cin >>a;
cout<<”\n enter the value of b ;
cin>>b;

 
- 82 -
Ideal C++

}
void sum()
{
c = a+b;
}
void display()
{
cout<<”\n first value :-”<a;
cout<<”\n sum is ”<<c;
}
};
void main()
{
clrscr();
demo d;
d.input();
d.sum();
d.display();
demo *p;
p = &d; or we can write
p input(); // (*p) . input();
psum(); //(*p) sum();
p display(); // (*p) . display();
getch();
}

Utility of Pointer:-
The concept of pointer is used for implementing concept of
polymorphism that is “dynamic data binding” (describe below)

Pointer to Derived Class:-


“Any base class pointer can hold the address of child class object”
Means pointer of object of base classes are type compatible with pointer to
object of a derived class.
By using this concept, concept of function overriding can be implemented.

FUNCTION OVERRIDING:-
It refers to multiple same name functions with same signature (structure)
within inherit classes called function overloading. It is a runtime polymorphism.

For eg.
class demo1
{
public:
void display ( )
{
cout<<”\n I am in demo1”;
}
};
class demo 2: public demo1
{
public:
void display()
{

 
- 83 -
Ideal C++

cout<<”\n I am in demo2”;
}
};
class demo3: public demo2
{
public:
void display()
{
cout<<”\n I am in demo 3”;
}
};
void main ()
{
demo3 d;
clrscr();
d. display();
}

Output - I am in demo3

Here always I am in demo3 will display because we are creating an object of


demo3 class and all parent classes (demo1 and demo 2) have same name functions that are
display but object is created of demo3 so always only demo 3 display will called.
So for calling other display function
1 Name must be changed:
If we change name then polymorphism will not be maintained.

2 Specify name of class while calling:


d. demo1 :: display();
d. demo2:: display();
d.dispaly();
By using this technique all function can be called, but here data abstraction will
not be maintained.
3 Use their owl class object: means create different objects but it will finish the utility of
Inheritance. So we can‟t create objects.

4 Concept of pointer will be used:


As we know that base class pointer can point to the object of child class so by
doing so parent classes or child classes both function can be called as given. Base class pointer
can only called on access. Only overridden function cannot be called other function. Means in
given program only display can be called of demo2 & demo3 but pointer of demo1 can call its all
functions.
void main ()
{
demo 1 *p;
p = new demo1();
p display(); // (*p) . display ();
p = new demo2();
p display(); // (*p) . display();
p = new demo3();
p display (); //(*p) . display(0;
getch();
}

 
- 84 -
Ideal C++

output>
I am in demo1
I am in demo2 NO
I am in demo3
(why) ?

Because the base class pointer cannot directly be used to access all the members
of the child class or derived class, we have to cast that pointer.
So temporary base pointer can convert to child class.

Typecasting of base class of object pointer to child class pointer:

 Pointer of base class cannot directly point to child class object means it can hold the
address of child class, but it cannot access member of child class directly, to do so we
have to convert it in child class, so that it can refer
 So again we will write main function like this:
void main()
{
demo1 *p;
clrscr();
p = new demo1();
p display();
p = new demo2();
((demo2*)p)display (0;
p = new demo3();
((demo 3*)p) display();
getch();
}
Now output is:
I am in demo1
I am in demo2
I am in demo3
It is called run time polymorphism, dynamic data binding, late data binding.
In such type of classes, at runtime the pointer is linked with a particular function,
means during compilation it cannot be justified that when function will invoke with which class,
that linking or binding will done at run time. So it is called runtime polymorphism (same name
function) or late data binding.
This type of implementation reduces readability and increase complexity of our
program.
So another alternate is also there, which implemented same thing but easier than
before one that is virtual function.

VIRTUAL FUNCTION:-

 Virtual function is another way of achieving the concept of runtime polymorphism.


 Concept:
o The functions when we use with the same name in both the base class and
derived class, the function in base class is declared as virtual using virtual
keyword.
 By making the function virtual c++ find out which function is to call at runtime based
on the type of object pointed by base class pointer rather than type of the pointer.

 
- 85 -
Ideal C++

Therefore by making the bases class pointer and when it holds the address of
its child then we can execute same named functions as per requirement.
 So rather than casting the pointer the concept of virtual function may be used which
increase the readability of our program. And decrease the complexity of our program.
 So whenever we want to implement the concept of function overriding, then virtual
function may be used to call different same name functions of different classes.

Implementation:-
class demo1
{
public:
virtual void display()
{
cout<<”\n I am in demo1”;
}
};
class demo2: public demo1
{
public:
void display()
{
cout<<”\n I am in demo2”;
}
};
class demo3: public demo
{
public:
void display()
{
cout<<\n I am in demo3”;
}
};
void main()
{
demo1 * p;
p=new demo1();
pdisplay();
p=new demo2();
pdisplay();
p=new demo3();
pdisplay();
getch();
}

now output

I am in demo1
I am in demo 2
I am in demo3
Here directly new operator is used that allocates the memory so no need to create
different objects without object display ( ) can be called directly by pointer.
So by making the virtual function, Polymorphism can be achieved in our
programming.
By making function as virtual the existence of function finish when another same
name function came into existence and different same name functions can be called easily.

 
- 86 -
Ideal C++

Some rules of virtual functions:-


1. Virtual functions always must be a member of any class.
2. Virtual can be a friend of any class
3. They are always accessed by pointers.
4. They cannot be static.
5. Virtual function must be defined even it is not used or call.
6. Virtual constructors are not possible.
7. Virtual destructors can be implemented.
8. No need that virtual function must be defined with in derived class.
9. The function header of all classes must be same in case of virtual function.
10. Runtime polymorphism is maintained by virtual function.

Pure Virtual Function:-

 Generally virtual functions are always refined within the derived class that is the actual
use of virtual function. (just to provide basic feature)
 Generally the function of base class is rarely used for performing any task because this is
already available in child class even in advance form.
It„s only play role of bases of functioning or place holder.
 So we can say these functions will not called any time now we can write this function like
this:
virtual void display() = 0;
 This is a “pure virtual function” these are also called “do nothing function”

Definition:-
 A pure virtual function is a function that is declared in the base class.
 It has no definition
 Initialize by zero
 It must be define within its child class otherwise child class also become abstract.
 A class which contains atleast one pure virtual function is called abstract class.
 An object cannot be created of abstract class.
 Used to maintain concept of polymorphism.
 If a class contains no. of different function and one is pure virtual function then this
class object cannot be created.
 Then how we can use or call another function:

 
- 87 -
Ideal C++

To use other child class so by using this class (child) functioning of parent class
can be used by its object.
 But one condition is these that this child must redefine the pure virtual function of
parent class in itself.
Otherwise itself it become abstract and its object cannot be created.

Polymorphism

Runtime Compile time


Polymorphism Polymorphism

Dynamic Static
Data Binding Data Binding

Runtime Polymorphism Compiletime Polymorphism

Late Data Binding Early Data Binding

Function Overriding Function Overriding


Operator Overloading

 
- 88 -
Ideal C++

Operator Overloading
Operators are special symbols which are used for manipulating data or values or operator.
Generally all the operators can directly manipulate the variables but operators
cannot manipulate objects, but we can say that objects are also variable of class data type. So
operators should also manipulate them. So finally it is possible, but user/programmer has to
write the code of operator to manipulate the object. It is called operator overloading and it is
included with in the concept of compile time polymorphism and it improve readability of our
code.
In C++, we can overload all most special operator so that they can perform
special operations on the object that we have created.
Basically these concepts also expand the meaning and functioning of operator.
After overloading the appropriate operator, we can use objects in expression in just the same way
that we use c++‟s built in data types.
“Operator” keyword is used for overloading the operators.

 Operator overloading is very easy. Create your function, write its code as per requirement
or write functioning here which you want to perform.
 Consider about the name of function.
o name of function = sign of operator
o Before sign operator keywords is used.
 Operator functions can be either member or non members of a class.
 Non member functions are almost friend of a class because friend is only non member
function which can access private member of a class and for manipulating members of
class friend is required.

Syntax of operator functions


Return type operator # (argument list)
{
body of operator functions
}
Here
 Operator is a keyword.
 # can be any operator (sign)
 Argument list: This specify the type and name of argument which operator require
for its functioning.
 We can implemented two type of operator
(1) Unary operator
(2) Binary operator

1 Unary operator:-
 It requires only one operand.
 So when we overload this type of operator the argument list will empty.

2 Binary operators:-
 Requires two operands.
 One argument is atleast must be there in argument list.

Consider following e.g. (without operand negation of two objects)


class demo
{

 
- 89 -
Ideal C++

int a,b;
public : demo() {} > default constant
demo (int x, inty)
{
a = x;
b = y;
}
void display( )
{
cout<<”\n value of a”;
cout<<”\n value of b”;
}
demo negative ()
{
demo z;
z.a = -a;
z.b = -b;
return z;
}
};
void main ()
{
clrscr();
demo d1 (10, 20);p
demo d2;
d2 = d1. negative();
d1. display();
d2. display ();
getch();
}
out put

value of a = 10
value of b = 20
value of a = -10
value of b = -20

Here d2 = d1. negative ( ) function will return new object which contain function to copy its
value and return to d2 object but in negative form
 more readable statement is :
d2 = -d1;
If we write this statement then error will occur, so now we are going to
implement or overload this unary operator.
Write this same program again but without using negative word for name of
function, -ve sign is used with operator keywords, if we do so this operator will be overload.
class demo
{
int a, b;
public: demo () {}
demo (int x, inty)
{
a = x;
b = y;
}
void display()

 
- 90 -
Ideal C++

{
cout<<”\n value of a”;
cout<<”\n value of b”;
}
demo operator - ( )
{
demo z;
z.a = -a;
z.b = -b;
return z;
}
};
void main()
{
demo d1 (10,. 20)
demo d2;
d2 = - d1; > unary operator overloading
d1. display();
d2. display ();
getch();
}

 Similar to this + operator can also be overloaded.

Overloading Of Binary Operator:-

(1) Overloading to +ve binary operator:


Implementation without operator by sum function:

class demo
{
int a, b; default constructor
public: demo( ) {}
demo (int x, int y)
{
a = x;
b= y;
}
void display ()
{
cout<<”\n value of a”;
cout <<”\n value of b”;
}
demo sum (demo p)
{
demo z;
z.a = a+ p.a;
z.b= b+ p.b;
return z;
}
};
void main()
{
demo d1 (10, 20);
demo d2 (100, 200)
demod3;

 
- 91 -
Ideal C++

clrscr();
d3 = d1.sum(d2);
cout<<”\n value of d1 object”;
d1. display();
cout<<”\n value of d2 object”;
d2. display ();
cout<<”\n value of added d3 object”;
d3 . display();
getch();
}
output:
Value of d1 object:
Value of a: 10
Value of b: 20
Value of d2 object:
Value of a = 100
Value of b = 200
Value of added d3 object
Value of a 110
Value of b 220

This same program can be written by + operator overloading only by writing operator +
at the place of sum like this:
class demo
{
int a, b;
public:demo ( ) {}
demo (intx, inty)
{
a = x;
b = y;
}
demo operator + (demo p)
{
demo z;
z.a = a+p.a;
z.b= b+p.b;
returnz;
}
void display()
{
cout<<”value of a”<<a;
cout<<\n value of “<< b;
}
};
void main ()
{
clrscr();
demo d1 (10, 20);
demo d2 (100, 200);
demo d3;
d3 = d1+d2;
d1 . display();
d2 . display();
d3. display();

 
- 92 -
Ideal C++

getch();
}
Output (same as before)

value of a = 10
value of b= 20
value of a = 100
value of b = 200
value of a = 110
value of b = 220

In this way within the same class all binary or required operators can be easily overloaded.
In the same program all binary operator (*, -, /, +) can be overload

class demo
{
int a, b;
public: demo () {}
{
a= x;
b= y;
demo operator + (demo p)

}
demo operator -(demo p)
{
demo z;
z.a = a –p.a;
z.b=b-p.a;
return z;
}
demo operator * (demo p)
{
demo z;
z.a = a* p.a;
z.b = b*p.b;
return z;
}
demo operator / (demo p )
{
demo z;
z.a = a/ p.a;
z.b= b/ p.b;
return z;
}
void display()
{
cout<<a<<”\t”<<b;
}
};
void main()
{

 
- 93 -
Ideal C++

demo d1 (100, 200), d2 (10, 20);


clrscr();
d1. display();
d2. display();
cout<<”\n *********”;
cout<<””\n addition is “ ;
d3. = d1+d2;
d3 . display();
getch();
d3= d1 - d2;
cout<<”\n subtraction is”;
d3. display();p
getch();
d3 = d1 * d2;
cout<<”\n multiplication is”;
d3. display();
cout<<”\n division is ”;
d3 = d1/ d2;
d3. display();
getch();
}
In this way with in a same class all binary or required operators can be easily overloaded.
 Suppose we want to add 5 values in an object like this:
d3 = d1+5;
So to do so, rather than passing the object d2 passed 5 as an integer value and use
following line of code.
demo operator+ (int n)
{
demo z;
z.a= a+n;
z.b = b+n;
return z;
}
 Suppose we want to write line as given:
d3 = 5 + d1;
Error will occur:
Because 5 is a value, it cannot call any function (operator function ) and d1 is an
argument, so no one is there to call the function but we known that d3 = d1+ 5 equal to
d3 = 5+ d1, to implement this case we have to run this above line.
Solution:
No one can call this function so here we will uses friend function because friend function
does not require any object for its calling so such type of problems are solved by friend function
.
For doing so:
 Friend functions declare with in class with friend key words.
 And define outside of class with two parameter one integer (any type) or one object
(sequence based).

Implementation of:
d2 = d1+5;
d3 = 5+d1;

solution >

 
- 94 -
Ideal C++

class demo
{
int a, b;
public:
demo ()
{
}
demo (int x, inty)
{
a = x;
b = y;
}
demo operator + (int n)
{
demo z;
z.a = n+a;
z.b = n+b;
return z;
}
friend demo operator + (int n, demo p);
void display()
{
cout <<”\n a =”<<a;
cout <<”\n b = ”<<b;
Output: =
}
};
demo operator + (int n, demo p)
{
demo z;
z.a = n+p.a;
z. b = n+p.b;
return z;
}
void main ()
{
demo d1(10, 20), d2, d3;
d = d1+d5; // run by normal function
d3 = 5+d1; // run by friend function
clrscr();
d1. display();
d2. display();
d3 . display();
getch();
}

a = 10 d1 object value
b = 20
a = 15 d2 object value
b = 25
a = 15 d3 object value
b = 25

 Here both functions can be over loaded using friend functions.

 
- 95 -
Ideal C++

Overloading of prefix & post fix


Inc/ decrement operator: =
d = d1++;
d3 = ++ d1;

Procedure:

demo operator ++ ()
{
demo z;
z.a = a++;
z.b = b++;
return z;
}
demo operator ++ ()
{
demo z;
z.a = ++a;
z.b = ++b;
return z;
}
Both are creating ambiguity because signature/prototype/structure of both
operators, functions is same so we have to remove this problem.

As we known ambiguity in overloading can be remove by different number of


argument and type of argument, we use this feature here:
 We pass integer one argument additionally to postfix operator. After that it will treat as
post fix operator (this thing is non optional, already defined to compiler)
 If we pass integer argument to prefix function then it will treat as postfix implementation
even its coding is prefix.
 The name of argument is optional.

Consider following e.g.:


class demo
{
int a, b;
public:
demo () {}
demo (int x, int y)
{
a = x;
b = y;
}
demo operator ++ ()
{
demo z;
z.a = ++a;
z.b++b;
returnz;
}
demo operator ++ (int n)
{
demo z;
z.a = a++;
z.b = b++;

 
- 96 -
Ideal C++

return z;
}
void display()
{
cout<<”\n ”<<”a = “<<a<<”\t<<”b = “<<b;
}
};
void main()
{
clrscr();
demo d1(10, 20) , d2 (10, 20)
d3 = d1++;
d4 = ++d2;
cout<<”\n value of d1 object ”;
d1. display();
cout<<”\n value of d3 object”;
d3. display();
cout<<”\n value of d2 object”;
d2. display();
cout <<”\n value of d4 object”;
d4. display();
getch();
}
Out put
value of d1 object
a = 10 b = 21
value of d3 object
a = 10 b = 20 postfix
value of d2 object
a = 11 b = 21
value of d4 object
a = 11 b = 21 prefix

In this way Inc/ dec operator can be overloaded.

Overloading of some special operators


Overloading [ ] subscript op.
class demo
{
int a[3];
public :
demo (int x, int y, int z)
{
a[0] = x;
a[1] = y;
a[2] = z;
}

int operator [ ] (int i)


{
return a[i];
}
};
void main ()
{

 
- 97 -
Ideal C++

demo d(10, 20, 30);


cout<<endl <<d[0] ; 10
cout<<endl<<d[1]; 20 output
cout <<end l <<d [2] ; 30
getch();
}
[ ] can also be used for assign values. To do this simply specifies return value of operator
[] () as reference use following statement:
int & operator [int i]
{
return a[i];
}
in main ( ) we can write now
d[1] = 100;
d[0] = 200;
Means rather than returning we can also assign values to these object by this operator.

Overloading ( ) Operator:-
class demo
{
int a, b;
public:
void display()
{
cout<<”\n a”<<a;
cout<<”\n b”<<b;
}
demo operator() ( int x, int y )
{
a = x;
b = y;
return (* this); - return object by which function call (invoke)
}
};
void main()
{
demo d1, d2;
clrscr();
d1(10, 20);
d2 (100, 200);
Out put d1. display();
a = 10 d2. display ();
b = 20 getch();
a = 100 }
b = 200

Overloading  operator
 class member access operator
 syntax :=
Object member;
class demo

 
- 98 -
Ideal C++

{
public:
int a, b;
demo * pointer  ( )
{
return this ;
}
}:
void main()
{
demo d;
d  a = 10;
d b = 20; // same as d.a = 10; , a.b = 20;
cout <<endl<<d a;
cout<<endl<<db;
getch();
}
Out put
10
20

It work like assignment operator but it is different.


[ () function must return a pointer to an object of the class that operator () operator
member must be accessible (public)].

OVERLOADING NEW & DELETE OPERATOR:-


In case of special situations, if we want some special memory allocation
method then we overload new & delete operator. If we don‟t overload than their by default
effect occur.
Suppose in cases of full of heap memory (user allocated area by O.S) and user
want to use hard disk memory as a virtual memory then we overload our own new and delete
operator.
Syntax:=
void * operator new (Size _t S)
{
Syntax for memory allocation
Constructor called
}
Return operator delete (void * p)
{
Remove block
Destructor called
}

Here size_t, defined type capable of containing the largest single piece of memory & will
contain the number of bytes needed to hold the object for which the memory is allocated.
 New function must return a pointer to the memory that it allocates.
 During this object constructor is automatically called.
 The delete function takes a pointer to the region (block) of memory to be fread.
 During this object destructor is called automatically.

 
- 99 -
Ideal C++

Special point:-
1. If these functions are defined with in a class then they work only for objects of this class.
2. If these functions are defined outside of a class then these operators can work for all
objects even for system data type (int, class)
e.g.
class demo
{
int a,b;
public:
void input()
{
cout<<”\n enter two values”;
cin>>a>>b;
}
void display()
{
coutM<<”\n a”<<a;
cout<<”\nb”<<b;
}
void operator new (size_t S)
{
void *p;
p. malloc (S);
cout <<”\n object created”;
return p;
}
void operator delete (void *p)
{
free (p);
cout<<”\n memory destroyed”;
}
void main()
{
demo *p = new demo ();
p input (); p display();
delete p;
}
Overloading of >>extraction and << insertion operator:-
These >> << operator are used with cin and cout object for inbuilt data type,
but suppose we want to use this operator to work for our objects then we overload these
operator for our objects.
Some points:
 Both overloaded by friend function.
 Both take two argument as reference
o One of stream (istream/ ostream)
o One our objects.
 Return reference of istream of ostream.
For e.g.:
 class demo
{
int a, b;
public:
friend ostream & operator <<(ostream &, demo);

 
- 100 -
Ideal C++

friend istream & operator <<(istream&, demo &);


};
ostream & operator (ostream & dout, demo d)
{
dout<<endl<<d.a;
dout<<endl<<d.b;
return dout;
}
istream & operator >>(istream & din, demo &d)
{
din>>d.a;
din>>d.b;
return din;
}
void main()
{
demo d;
clrscr();
cin>>d;
cout<<d;
getch();
}

Rules For Overloading Operator:-


1. Basic meaning of operator must not change.
2. Only existing operator can be overload.
3. New (arbitrary) operators cannot be overload.
4. The overload operator must have atleast one user defined data type (object).
5. Overload operators must follow actual operator syntax.
6. Required no. of argument must always be provided.
7. Unary operators do not take any argument if they are not friend function.
8. Binary operator always take one argument if they are not friend function, if they are
friend then two arguments must there.
9. While overloading binary operator, the left hand operator must be an object of related
class (in which it is defined)
10. 10. Two syntax can by used for calling operator
d3 = d1+ d2; (more redable)
d3 = d1 . operator + (d2);
11. Some operators cannot be overloaded because they have their own meaning and they
itself used for calling some sort of internal feature that cannot be written by programmer. So
they cannot be overloaded.
1 size of operator
2 . dot operator
3 .* pointer to member access operator
4 : : scope resolution operator
5 ? : ternary operator
12 . Some operator cannot be overloaded by friend function.
Because these operator always require object (calling), friend does not require any object
for calling it.
1 = assignment operator
2 ( ) function call operator
3 [ ] subscripting operator
4  class member operator

 
- 101 -
Ideal C++

Exception Handling

While develop a program there are two types of errors.


(1) Compile Time
(2) Run Time

(1) Compile Time Error:- There are generally logical errors and Syntax errors and
because of these error program cannot run. (Syntax Error)

(2) Runtime Error:- There are some other errors than logic or syntax errors. They are
now as Exception.
Runtime Error = Exception
Exceptions are runtime Anomalies or unusual conditions that may occur while executing the
program.

When user write the code to handle this unusual errors while executing program it is called
“Exception Handling”.

Some Runtime Errors (Exceptions) are:-


 Divide by zero
 Wrong type of value
 Access array out of its boundary
 Running out of memory or disk
 Wrong value in an array, etc.

ANSI C++ provides built in features to detect and handle these runtime errors is called
Exception Handling.
There are two type of Exceptions
1. Synchronous Exception
2. Asynchronous Exception

1. Synchronous Exception:- Exception which can handled by programmer is called


Synchronous Exception.

2. Asynchronous Exception:- Exception which cannot handled or out of control of


program is called Asynchronous Exception. Eg- Keyboard Interrupt.

Exception Handling in C++ is based on three keywords.


Try
Catch
Throw
Try Block:-
Statements which can generate the exception must be written within try block.

Throw:-
When any exception occurs, then try throw statement is called to throw this exception.

Catch:-
Catch block contains statements which can handle the exception when throw by try block.

 
- 102 -
Ideal C++

Catch always written exactly after try block.


Exception is handled by catch block and exception itself is an object, that pass the exception
from try to catch block.
The purpose of Exception handling is to provide mechanism by which program can be run
appropriately.

IMP Generally which any exception occur or runtime error occur then at this point program
will be terminated and remaining line of code cannot execute in any case, it is called Abnormal
Program Termination(APT) and it is done by abor ( ) function of O.S.

 Our purpose is that, if any runtime error occur then program must not terminated and
remaining line of code should be executed normally, this task is done by Exception Handling.

While doing Exception Handling, following task is performed:


I. Hit the Exception
II. Throw the Exception
III. Catch the exception
IV. Handle the Exception

Block Diagram:-

Try Block
Detect and
throw an
exception
Exception
Object

catch and
handle an
exception

When the try block throws as exception, the program control leaves the try block and
enters the catch statement of the catch block.
Exceptions are objects used to transmit information about a problem.
If type of object thrown, matches the arg type in the catch statement, then catch block is
executed for handling the exception.
If they do not match, the program is aborted with help of abor() function which is called
by default.

When exception is not detected in try block and not thrown, then the control goes to the
statement immediately after the catch block.

Eg:-
void main()
{
int a, b;
clrscr();
cout<<”\n Enter value of a:- “;
cin>>a;
cout<<”\n Enter value of b:- “;

 
- 102 -
Ideal C++

cin>>b;
c=a+b;
cout << “Addition is :- “<<c;
c=a/b;
cout << “Division is :- “<<c;
c=a*b;
cout << “Multiplication is :- “<<c;
c=a-b;
cout << “Subtraction is :- “<<c;
getch();
}

Output:-
If we input 20 10
Addition is :- 30
Division is :- 2
Multiplication is : -200
Subtraction is :- 10

If we input a=10 and b=0


Then c=a+b perform efficiently.
But when c=a/b perform, then program will terminated because it is Runtime error and c=a*b
and c=a-b will not execute so we use exception handling to solve this problem.

void main()
{
int a,b,c:
clrscr();
cout<<”\n Enter value of a & b:-“;
cin>>a>>b;
c=a+b;
cout<<”\n Addition is :-“<<c;
try
{
If(b!=0)
{
c=a/b;
cout<<”\n Division is “<<c;
}
else
throw b;
}
catch(int x)
{
cout<<”\n Wrong Value of b: Exception”;
}
c=a*b;
cout<<”\n Multiplication is :- “<<c;
c=a-b;
cout<<”\n Subtraction is :- “<<c;
getch();
}

If we input 10 and 0 in a & b


Then output:

 
- 103 -
Ideal C++

Addition is:- 10
Wrong value of b: Exception
Multiplication is:- 0
Subtraction is:- 10

Here in such cases because of o, program should terminate but it run because of Exception
Handling.
Normally because of zero(0) program terminate at c=a/b point but here we have use
exception handling so error point will handle and remaining line of code will execute as it is.

Throw Concept:-
There are three technique of throwing an Exception.

throw exception; normal throw


throw (exception);
throw ; rethrowing the exception

Special Point:-
Throw point can be nested within a try block, in every case control is transferred
to the catch statement.
try
{

}
catch (object);
Catch Exception:- {
}
Catch block is always execute when try block throw an exception and if type
match.

 The argument name is an argu.list of catch block is optional, means if you use arg. In catch
block then specify the name otherwise not.

catch (int x)
{
cout<<”\n Integer Exception: - “<<x;
Both are same

}
catch (int )
{
cout<<”\n Integer Exception: - “<<x;
}

 
- 104 -
Ideal C++

 If try block throw any exception and if catch block not exist then abnormal program
termination will occur.
 Catch block is simply skipped if the catch statement does not catch an exception.

Multiple Catch Statements:-


Sometime it may be possible that try block can have multiple throw statements of
different type then multiple catch statements can also there. (similar to switch statements)

try
{

}
catch (type 1)
{

}
catch (type 2)
{

}
:
:
catch (type n)
{

 Only single argument must be there.


 When an exception is thrown, the exception handlers are searched in order for mach.
 If catch block match, then remaining skip and after all catch block statement will execute.

When no match found, then program will terminate.

void test( int n)


{
try
{
if(n==1)
throw 10;
else if(n==2)
throw 98.63;
else if(n==3)
throw „A‟;
else
cout<<”\n No Exception”;
}
catch (char x)
{

 
- 105 -
Ideal C++

cout<<”\n Exception Caught:- char”;


}
catch(int x)
{
cout<<”\n Exception Caught:- int”;
}
catch (double x)
{
cout<<”\n Exception Caught:- double”;
}
cout<<”\n End of Test”;
}
void main()
{
clrscr ();
cout<<”\n I am in main”;
test(1);
test(2);
test(3);
test(4);
cout<<”\n End of main”;
getch ();
}
Output:-
I am in main.

Exception caught: int


End of test

Exception caught: double


End of test

Exception caught: char


End of test
No Exception
End of Test
End of main.

Here try block does not throw any Exception when n =4.

Catching All Exception:-


Whenever we want to write only a single catch block that can catch all type of
throw exception then rather than writing the different catch block we can write following which
can catch all exception.

catch ( . . . )
{ This triple dots exception can catch
Statements; all type of Exception
}

So no need to write different – different catch block


 But

 
- 106 -
Ideal C++

When we want to perform different-different task or want to execute different-different


statements for different-different exception, then there is a need to write separate statement of
catch.

IMP If we write both normal and … catch block then it must (…) be written after all catch
block, otherwise it will catch all exception, no use of remaining catch block.

Throw point():-
The point at which the throw is executed is called throw point.

Imp Once and exception is thrown to the catch block, control cannot return to the throw
point.
Exceptions are often thrown by functions that are invoked from within try blocks.

type function (arguments)


{
throw (object);

}
ry
{
Calling of function
}
catch(argument type)
{

Eg:-
void divide(int
{
if(b!=0)
{
int c;
c=a/b;
cout<<”\n Division is:- “<<c;
}
else
throw b;
}
void main()
{
try
}
divide(20, 10);
divide(10,0);
}
catch(int x)
{

 
- 107 -
Ideal C++

cout<<”\n Exception Caught”;


}
getch();
}

Output:
Division is :- 2
Exception Caught.

Rethrowing an Exception: -
Sometime it may be possible that a catch block (handler) cannot handle the
exception then it can rethrow that exception to other catch block, this is called Rethrowing an
Exception.
In such situations, we may simply write throw without any argument.
throw;

If we use this, it will throw the current exception to another catch block listed
after try block or to other catch catch group.

 Here catch group refers to group of catch block that are used for rethrowing the exception.
 catch groups are automatically created when any statement included within catch block series
then this statement separate the catch and create catch group.
 If catch throw any exception then another catch group catch statement, catch the exception.

Eg:-
void divide (int a, int b)
{
try
{
if(b!=0)
{
c=a/b;
cout<<”\n Division is: -“<<c;
}
else throw b;
}
catch (int x)
{
cout<<”\n Exception: Wrong Value”;
throw; || rethrowing an Exp
}
}
void main()
{
try
{
divide(20, 10);
divide(10, 0);
}
catch (double)
{
cout<<”\n Exception Again caught”;
}
cout<<”\n End of main”;

 
- 108 -
Ideal C++

getch();
}

Output:-
Division is:- 2
End of main
Exception: Wrong Value
Exception Again Caught
End of main

Throw List:-
It is possible that user wants, function should throw only some specified exception. This
can be done by adding a throw list to function definition.
Means we want to restrict a function to throw any Exception then this restriction is done
by throw list, if we specify exception in throw list, then function will not throw any exception.

Syntax: -
Type function(arg list)
{ throw (type list)

If we want that function should not throw any exception then we can do so by making the throw
list empty like this:
throw();

 If we include such type of statement within definition of any function then this function will
not throw any exception.

For eg:-
void test(int n) throw(char, int)
{
if(n==0)
throw „A‟;
else if(n==1)
throw ;
else if(n==2)
throw 98.63;
else
cout<<”\n Normal Execution”;
}
void main()
{
try
{
test(0);
test(1);
test(2);
test(3);
}
catch(int x)
{
cout<<”\n Integer Exception”;

 
- 109 -
Ideal C++

}
catch(float x)
{
cout<<”\n float Exception”;
}
catch(char x)
{
cout<<”\n Character Exception”;
}
cout<<”\n End of main”;
getch();
}
Output:-
Float Exception
Normal Execution
End of main

 In this way, we can restrict any function to throw exception


 And if we include empty throw() list then output:
Normal Exception
End of Main.

 
- 110 -
Ideal C++

Namespace
Generally only single name variable or single name identifier can be declared with
in a scope. Means with in any scope only single name variable can be defined. If we define,
collision will occur because of same name but if we want to declare multiple variable of same
name then concept of namespace is used.
Namespace is actually a name of a block which can be used for avoiding the name
collision.
“A namespace is simply a declarative region”
Element declared in one namespace are separate from elements declared in
another namespace. When we include a new style header in our program, the contents of that
header are contained in the “std” namespace.
Std is a standard namespace already created within ANSI C++
All classes functions and templates are declared with in the namespace named
std. That‟s why we use using namespace std; statement so that we can use the members of std
namespace within our code otherwise we have to use : : operator with element of namespace like
std: : cin>>a; std : : cout<<a;

Defining A Namespace:-
We can define namespace of our own as per our requirement.
 For defining the namespace the key word “namespace” is used.
 Syntax is similar to defining the class.
Syntax:
namespace name  user given
{
Declare
Variable --------
Functions -----
Classes-------
}
 Generally it is defined outside of any block.
 namespace does not terminate with semicolon (;) like class.
 Member variables can also be initialized within namespace.
 Members of namespace can be directly used with its name with SRO operator; we need
to create its object like class. It is only a block for proper separation.
Eg
namespace sp
{
int a = 10;
int b= 20;
}
int a = 100;

void main ()
{
int a = 1000;
cout<<”\n value of local a;”<<a;
cout<<”\n value of global a”<<::a;
cout<<”\n value of namespace a:”<<sp::a;
getch();
}

 
- 111 -
Ideal C++

output :
value of local a – 1000
value of global a- 100
value of namespace a- 10

By using this namespace multiple same name variables can be defined and they are
recognized according to namespace.
 Accessing of namespace member
Syntax:
namespace :: member_name;
As in previous example a was accessed by
sp:: a;
 We can also initialize member of namespace outside of namespace with the same above
structure
sp:: a= 100;

Member of namespace can be used with out their (namespace) name, but we
have to qualify them within the scope where we want to access namespace member.
Where we want to include any namespace with in scope environment, it is called
“qualifying” namespace.
Syntax:
1. using namespace name;
2. using namespace_name :: member name;
By using (1) statement entire namespace is included with in block.
By using (2) statement only member of namespace can be included with in block.

Special point:-
 If we include namespace in any scope and it also contain same name member then
namespace variable will get hide and if we want to access it them namespace name
and again SRO is used.
 Multiple namespace can be included but same name members must not be there in
all namespace.

e.g. qualifying namespace


namespace sp1
{
int a= 10;
}
namespace sp2
{
int a = 20;
}
void main ()
{
clrscr();
using namespace spl;
cout<<”value of sp1”<<a;
cout<<”\n value of sp2 ”<<sp2::a;
getch();
}

 
- 112 -
Ideal C++

Now we have included sp1 so no need to use sp1:: with a of spl because it is directly
available but we have to use name of sp2 because it is not directly qualified yet.

case 2:
namespace sp1
{
int a= 10;
}
void main()
{
int a = 100;
using namespace sp1;
cout<<”\n value of a”<<a;
cout<<”\n value of sp1a<<a;
getch();
}

Both will print 100, because main also has a with 100 and its priority is highest.
That‟s why namespace sp1‟s a will get hidden.
 To access a of namespace then even using of sp1, sp1 and SRO will be used.
cout<<”\n value of sp1‟sa ”<<sp1 ::a;

Now output is ;=10

case 3 : multiple namespace can also be include


namespace sp1
{
int a = 10;
}
namespace sp2
{
int b= 20;
}
void main ()
{
int c= 30;
using namespace sp1;
using namespace sp2;
cout<<”\n value of a” <<a;
output cout<<”\n value of b”<<b;
cout<<\n value of c “<<c;
getch ();
}
value of a 10
value of b 20
value of c 30
case :

Case: Only required member of namespace can also be included by using


keyword.

namespace sp
{
int a=10;

 
- 113 -
Ideal C++

int b= 20;
}
void main ()
{
using sp :: a;
clrscr();
cout<<”\n value of a”<<a;
cout<<”\n value of b”<<sp::b;
getch();
}

Here a is used directly and b not because only a is included with in main ( ) scope
 So by using above concept only required member of namespace can be included or
qualified.

case :
namespace can also have functions;

namespace sp
{
int a;
void display()
{
cout<<”\n value of a”<<a;
}
}
void main ()
{
sp : : a = 50;
sp :: display(); getch();
}

Or we can include this namespace, so no need to write name of namespace during use.
void main ()
{
using namespace sp;
a = 50;
display();
getch();
}

Case: Namespace functions can also be define outside of namespace like in class, with SRO
and this must be declared within namespace.
namespace sp
{
int a;
void display();
}
void sp ::display()
{
cout<<”\n value of a”<<a;
}
void main ()
{
sp :: a= 500;
sp:: display();

 
- 114 -
Ideal C++

getch();
}

 Function is defined outside namespace only to reduce the complexity of namespace.


 This function cannot be a member of class of namespace [namespace can also contain
class as a member]

Case: namespace can also contain an entire class definition as its member
namespace sp
{
class addition
{
int a, b,c;
public :
void input ()
{
cout<<”\n input two values ”;
cin>>a>>b;
}
void sum ()
{
c = a+ b;
}
void display()
{
cout <<”\n the sum is ”<<c;
}
};
}
void main ()
{
clrscr();
sp:: addition d;
d. input ();
d. sum();
d. display();
getch();
}

Unnamed Namespace:-
A namespace which has no name is called unnamed namespace.
Means, we can also define any namespace without its name.
If we do so, then members of this namespace become global, means this type of
declaration is similar to defining global member.
 Unnamed namespace are used directly with in scope because they have no name.
 Unnamed namespace member can also be used between files.
 Every file (program ) has its own unique unnamed namespace.
namespace sp
{
int a = 10;
}
namespace
{
int a = 100;
}

 
- 115 -
Ideal C++

void main ()
{
cout<<”\n value of sp a”<<sp:: a;
cout<<”\n value of a”<<a;
}

Nesting of Namespace:-
A namespace which can also have another namespace is called nesting of
namespace.
 Outer namespace : in which another namespace exist
 Inner namespace : when outer namespace contains another name
space as member is called inner namespace.
namespace sp1
{
int a= 10;
namespace sp2
{
int b= 20;
}
}
void main ()
{
clrscr();
cout<<”\n value of a”<<spl::a;
cout<<”\n value of b”<<sp1:; sp2::b;
getch();
}
When we include outer namespace then inner cannot include directly,
inner has to include again with the name of outer.
 Suppose we want to include both sp1 and sp2 in our program (main), then we have to
write following line of statements:
void main ( )
{
using namespace sp1;
using namespace sp1::sp2;
cout<<”\n value of a”<<a;
cout <<”\n value of b”<<b;
getch();
}

Here sp2 cannot be included directly because it is defined with sp1, so whenever
we want to use sp2, we have to use name of sp1, because of nesting.

 
- 116 -
Ideal C++

Standard Template Library


As we know that template can be used to create generic classes and functions that
are used for performing operations on various data type called generic programming.

Alexander Stepanou and Menglee developed a set of general purpose templatized


classes and functions used for storing and proceesing of data. The collection of these generic
classes and functions is called “Standard Template Library” (in ANSI c++)

Components of STL:-
Basically there are three basic components of STL
1 Containers
2 Algorithm
3 Iterators

“Algorithm employs iterators to perform operations stored in containers”

1. CONTAINERS:-
A container is an object that actually stores data. The task of container is to
organize data with in memory.
Containers are implemented by template classes so that they can be easily handle
different types of data.
 There are ten different containers, categorized in three different categories:

Containers

Sequence Associative Derived


Containers Containers Containers

Vector Set Multiset Map Multimap Stack

Deque Queue

List Priority
Queue

STL components are defined in the name space [std] that‟s why we have to use the using
name space std directives to inform the compiler that we want to use features of STL.

Sequence Containers:-
Sequence containers store the element with in a linear sequence just like a line. Each
element is related to other by its position (linked list).
There are three types of sequence:

 
- 117 -
Ideal C++

Containers:
1 Vector 2 List 3 Deque
 Elements in all these containers can be accessed using an iterator, but the difference is in
their performance of insertion and deletion of elements.
 Table shows performance:
container random access insertion at middle deletion at end
vector Fast slow fast at back
list Slow fast fast at front
Deque Fast slow fast at both (a-b)

Vector:-
 It is a dynamic array.
 Allows direct access to any element.
 Random access iterator is used.
 <vector> header file is used.
List:-
 It is a linear list.
 Insertion and deletion can be done anywhere within a list.
 It is of bidirectional nature.
 <list> header file is used.

Deque:-
 It is a double- ended queue.
 Insertion and deletion can be done at both front and rear
 Allows direct access to any element.
 Random access iterator is used.
 <deque> header file is used.

2. Associative Containers:-
These containers are basically design to create key- value relationship, means
element or value can be accessed using keys.
These are not sequential.
There are four types:
1. Set
2. Multiset
3. Map
4. Multimap
 These all containers stores data in a special structure called tree, so that fast searching
insertion and deletion can be performed.
 Very slow for random access and not suitable for sorting.
 Generally these containers are used for implementing concept of value key relationship.

1. Set/ Multiset:-
These containers can store a number of elements and facilitates various
operations on these numbers using keys.
 These elements are stored along with their keys and there elements can accessed by these
keys.
User fires the key then associative value can be accessed from these containers.

 
- 118 -
Ideal C++

 Eg
Set can store objects of employees which are ordered either in ascending or descending
order/ sequence.
We can search required employee by hid id as the key
Set and multiset both are same but major difference is:
Set does not all duplicate values or element, where as multiset both are
bidirectional and <set> header file is required.

2. Map/Multimap:-
These containers are used to store pairs of element, one called key and
the other called value we can manipulate these pairs using their associated keys these
values are also called mapped values.
Basic difference between map and multimap is that,
 Map allows only one key for a given value where as
 Multimap allows multiple keys for a given value
 map base on one to one mapping
 Multimap based on one - to many mapping
 Both require <map> header file
 Iterator are bidirectional
 When mapping is required then the concept of map and multimap is used
 It requires two types in the template one for and key and one for value.

3. Derived Containers:-
 These are also called “Containers Adaptor”
 There are three derived containers:
1. Stack
2. Queue
3. Priority – queue
 These above three containers are created from different sequence containers, that‟s
why they called “Derived Containers”.
 They do not support iterators because they all are rule based such as
Stack (LIFO), Queue (FIFO) Priority-queue (priority - based)
 Queue and priority queue requires <queue> header file.
 Stack has <stack> header file.
 Generally push ( ) and pop ( ) functions are used for insertion and deletion operations.

2 ITERARTORS:-
 Every container has their own associated iterators.
 They behave like pointers.
 They are used to access container element.
Means for performing any operation on container element these iterators are
used.
 Different type of access provided by different iterators.
 Iterators are already associative with their container.
 Nature of iterator is based on type of container.
 Basically there are 5 types of iterator :

 
- 119 -
Ideal C++

RANDOM ACCESS
BIDIRECIONAL
FORWARD

Input Output

DESCRIPTION OF ITERATORS:-
1 Input Iterators:-
 Support least functions.
 Used only to traverse in containers.
 Access method linear.
 Direction of movement  Forward only.
 I/O capability  Read only (as name).
 Cannot be hold.
 Operator used  ++, = = , !=

2 Operator Iterator:-
 Support least functions.
 Used to traverse in container.
 Access method  linear
 Direction of movement  Forward only
 I/O capability Write only
 Cannot be hold(save))
 operator used : ++

3 Forward Iterator:-
 Support all the operations of Input and output iterators and retains its position.
 Access method Linear
 Direction of movementForward only
 I/O capability: read / writes
 Position can be hold/ saved.
 Operator used: ++ = = ,! =

4 Bidirectional Iterator:-
 Suppose all the operations of Input/Output and forward iterator.
 Give the facility to move in backward direction in containers.
 Direction of movement  Forward & Backward.
 I/O capability  Read & Write.
 Position can be saved.
 Operator used:
++ -- == !=
| |
Forward Backward

 
- 120 -
Ideal C++

5 Random Access Iterator:-


 Support all the features of all previous iterators.
Main difference is that,
It has an ability to jump to any location (arbitary)
 Access methodRandom
 Direction of movement  Forward & Backward
 I/O capability  Read & Write
 Position can be hold
 Operator used: ++, --, + - ! = <> <= >= = = + = - = (shorthand operator.)

These all are basic iterators which are used for traversing / accessing container
elements.
Generally declaration of an iterator with container specifies the type of iterator,
no need to define its name.

Syntax:
Container iterartor :: iterator name

Name of container keyword used define name

4. ALGORITHM:-
Some features are common for all the containers almost, rather than
define these features for all the containers they are defined separately, to save code; these
are define d in algorithm category.
Algorithms are functions that can be used by almost all containers for processing
their contents.
These algorithms allow us to work with two or more different type of containers
at the same time.
These algorithm are not member function of containers so, no need to use object
while using them.
 They are not friend also.
 These are stand alone template functions.
 To use this algorithms <algorithm > header file is used.

Based on the nature of operation or type of functioning algorithm are divided into five
different categories:
1 Retrieve or non mutating algorithms.
2 Mutating algorithm.
3 Sorting algorithm.
4 Set algorithm
5 Relational algorithm
There are almost 70 algorithms:
For eg:
 random _ shuffle ( ); place elements in random order.
 replace ( ); replace element with specification value
 sort ( ); sort the element
 merge ( ); merge two sequence
 set_union ( ); generate sorted union of two ordered sets
 min ( ); gives minimum of two values
 max ( ); gives maximum of two values

 
- 121 -
Ideal C++

Vector Container:-
 Mostly used containers.
 Stores element in contigous memory locations.
 Direct access to element by [ ] subscript operator.
 Change its size dynamically.
 Syntax for creating objects
vector <int> v; // int type vector of 0 size
vector <int > v(10); //int type vector of 10 size
vector <int> v1(v2); // create v1 from v2
vector <int> v(10, 5) ; // create vector of 10 element with 5 value in
all block
 Some method of vector class:
o at ( ) : return reference to an element.
o back ( ) : gives reference (iterator) to last element.
o begin ( ) : gives reference to first element.
o resize ( ) : change the size of vector.
o size ( ) : gives no. of elements.
o swap ( ) : exchange elements of two specified vector.
o pop_back( ) : delete last element.
o push_back ( ): insert element at end.
o erase ( ) : delete specified element.
o insert ( ) : insert element at specified location.
o clear ( ) : delete all element.

Implementation of vector:
#include<iostream .h>
#include <conio,h>
#include<vector>
using name space std;
void main ( )
{
int n;
vector v(10);
clrsccr( );
for (int i= 0; i < 10; i++ )
{
cout<<”\n enter element ”;
cin>>n;
v. push – back (n);
}
cout <<”\n size of vector ”<<v. size ();
int i;
cout <<”\n element of vector”;
for (i=0; i<v.size( ); i++)
cout <<endl<<v[i];
v. push - back (500);
v. push – back (900);
cout <<”\n size of vector”<<v. size ();
cout <<”\n element of vector”;
for (i= 0; i<v. size(); i++)
cout <<endl<<v.at (i) ; // same as v[i]

//display through iterator


vector <int> :: iterator itr;

 
- 122 -
Ideal C++

itr = v. begin ();


cout <<”\n contents of vector”;
while (itr <.vend ())
{
cout <<endl<<*itr;
itr ++;
}
itr v. begin ();
itr = itr + 4;

v.insert (itr2, 99);


//it will insert 99 twice time at itr location
for (i=0; i<v. size(), i++)
cout <<endl<<v[i];
getch();
v. erase (itr, itr +3);
// it will erase delete itr to after
//2. element
cout <<”\n contents of vector are now”;
itr = v.begin();
while (itr< v.end(0)
{
cout <<endl<<*itr;
itr ++;
}
v. clear();
cout <<”\n now size of vector ”<<v. size ();
//display 0
getch();
}
Here we can access the element either by; loop or iterator.

LIST:-
 List can be accessed sequentially.
 Iterators are used
 Some method of list containers:
o back ( ) : gives reference to last element.
o begin ( ) : gives reference to first element.
o clear ( ) : delete all elements.
o end ( ) : gives reference to end of list.
o merge ( ) : merge two ordered list.
o reverse ( ) : reverse the list.
o sort ( ) : sort the list.
o pop_back ( ): delete last element.
o pop_front ( ) : delete first element.
o push_back ( ) : insert element at last.
o push_front ( ) : insert element at first.
o remove ( ) : remove element at specified location.
o size ( ) : return total elements.

Implementation of list:-
#include <iostream .h>
#include<conio.h>
#include <list>
using name space std;

 
- 123 -
Ideal C++

void main ()
{
int n, I;
list <int> l1 (5);
list <int >l2 (10);
// insertion in l1 by function
for (i=0; i<5; i++)
{
cout<<”\n enter element”;
cin>>n;
1. push - back (n);
}
// insertion in l2 by iterator
list <int> :: iterator itr;
itr = l2 . begin ();
while (itr! = l2 . end ())
{
cout<<”\n enter element”;
cin>>n;
itr = n;
itr ++;
}
cout <<”\n element of list”;
itr = l1. begin ();
while (itr != l2 . end ())
{
cout <<endl <<itr;
itr++;
}
cout<<”\n element of l list ”2;
itr = l2 .begin ();
while (itr ! = l2 .end())
{
cout<<endl<<*itr;
itr ++;
}
1. sort ();
2 .sort ();
itr = l1 begin ();
while (itr != l2 . end())
{
cout<<endl<<*itr ;
itr++;
}
getch();
}

5. MAP:-
It is a sequence of (key value).

Key1 Val1

Key2 Val2

Key3 Val3
| |
| |

Keyn Valn

 
- 124 -
Ideal C++

Some method of map container:-


 begin ( ) : gives reference to first element.
 end ( ) : gives reference to end of map.
 clear ( ) : delete all elements from map.
 size ( ) : gives no. of elements of map.
 swap ( ) : interchange the elements of two maps.
 insert ( ) : insert elements at specified location.

Implementation of map:-
 Here we are maintaining emp id
(Key) and his salary (value)
#include<conio.h>
#include<iostream.h>
#include<map>
using name space std;
void main ()
{
map <int , int>e;
int id , sal;
clrscr();
cout<<”\n enter id & sal of 5 employee”;
for (i=0; i<5; i++)
{
cout<<”\n enter id”;
cin>>id;
cout<<”\n enter salary”;
cin>>sal;
e[id] = sal; // put in map
}
cout<<”\n size of map ”<<e size ();
e[106] = 7000; // manually insertion.
//display key & value :
map int , int > : iterator itr;
itr = e. begin ();
while (itr ! = e. end())
{
cout <<endl<<itr  first <<”\t”<<\t <<itr  second ;
itr ++;
}
/* Here first and second pointer points to the keys and value of map and through this
pointer we can access this both */
/* directly accessing of element
couty<<”\n enter employee id”;
cin>>id;
cout<<id <<”salary is”<<e[id];
getch();
}

 
- 125 -
Ideal C++

FILE HANDLING
Introduction:
We all know tha RAM is a volatile memory and any data stored in RAM is lost
when PC is turned off. All the programs we have seen so far have made use of RAM. Any
data variable that we define in our program is destroyed when the program execution is over.
Also the outputs generated by the program are lost.
One solution may be to take printouts of the program and outputs. They may
help up to a creation extent but that is not appropriate for the practical purpose. Therefore in
most real word applications data is stored in text files which is stored permanently on to the
hard disk, floppy, compact disk or in any other persistent storage media. These files can be
read back again. And can be modifierd also.
A data file is a collection of data items stored permanently in persistent storage area.
The C++ language provides the facility to create these data files. Write data into them.
Read back data. Modify them and many more operations. The program data or output can
be stored in these files and that persists even after program is over. The data can be read
whenever necessary and can be placed back into the file after modification. The data remain
safe provided storage media does not crash or corrupt.
From permanent storeage point of view, a file regaion of memory space in the persistent
storage media and it can be accessed using the built-in library functions & classes available in
header file insotream.h or by the system calls of the operating system. High Level Files are
those files which are accessed and manipulated using standard functions. For transfer of the
they make use of streams. A stream is a pointer to a buffer of memory, which is usedfor
transferring the data. In general stream can be assumed as a sequcace of bytes which flow
from source to destination. An IO Stream may be text stream or binary stream depending
upon in which mode you have opend the file. A text stream contains lines of text and the
characters in a text stream may be manipulated as per the suitability. But a binary stream is a
sequence of unprocessed data without any modification. The Standard IO Stream or stream
pointer are cin(for reading). Cout(for output). And eerr(for error). By default cin represent
keyboard. Stdout and stderr represents monitor or VDU.
Low level files make use of the system-calls of the operating system under which the program is run.

FILE STREAMS
In C++ there are three main classes for handling disk files input and output. They are:
(A) Ifstream
(B) ofstream
(C) fstream
(a) The ifstream class is an istream derivative specialized for disk file input. Its
constructors automatically create and attach a filebuf buffer object. A file can be
created by the constructor method or using the open method of ifstrem class. For
Clasing the file close method can be used. Ifstream can only be used for readin a file.
(b) The ofstrem class is an ostream derivative specialized for disk file output. All of its
constructors automatically create and associate a filebuf buffer object. A file can be
created by the constructor method or using the open method of ofstrem class. For
closing the file close method can be used. Ofstream can only be used for writing to a
file only.
(c) The fstream class is an iostream derivative specialized for combined disk file input
and output. Its constructors automatically create and attach a filebuf buffer object. A
file can be created by the constructor method or using the open method of fstream
class. For clasing the file close method can be used. The fstream class can be used for
reading, writing, appending or doing any other operation as we will see shortly.

 
- 126 -
Ideal C++

OPENING AND CLOSING A FILE


For opening a file any of the above discussed file streams can be used. For opening a file
for reading only we can use ifstrem class as:

(a) ifstream rdfile(“demo.txt”);


The above method creates an object of class ifstrem type and attaches it to the
file “demo.txt”. The files is opened for read only. The object is created by calling
the constructor of the class ifstrem and pssing an argument of char* type which
is file name to open. As soon as file is opened for read mode. File pointer is
placed at the beginning of the file. We assume that there is no error in opening
the file. Error handling will be discussed later on. Assuming the file is opend
successfully. We can now read from the file as

char str[10];
file>>str;
The string read from file (assume file contains a string “hello”) will be
stored in the variable str The file can be closed later be calling the close method
of the class as

file.close( );
Calling close method ensures all data stored in the buffer related to the
file will be written to the disk and all links will be broken. Always make a practice of clasing a file
when you are done with the file.

(b) ifstrem rdfile;


refile.open(“demo.txt”);

This is the second method of opening the file. Here first an object of ifstream class type
is created. We then open the file using the open function of the ifstream class.
On the similar grounds we can open a file for writing only by ofstream class as.

(a) ofstream wrfile(“demo.txt”);


(b) ofstream wrfile;
wrfile.open(“demo.txt”);

Explanation for the above methods is similar to the explanation as given for the ifstream
class. The data can be written to the file as
wrfille<<”hello”;
The file can be closed as
Wrfile.close();

The ifstream class and ofstream class are suitable only when we want to read from file or
write only to the file. In situations when we want to perform reading and writing to the same file.
There are two ways : first is to create two separate object of ifstream and ofstream class. When
writing is done, cloase the file and open the file for reading using an object of ifstream class. The
second method is to create just one object of class fstream class and use as:

 
- 127 -
Ideal C++

fstream filel;
file.open(“demo.txt”,ios::out);
//perform writing operation;
file.close();
file.open(“demo.txt”,ios::in);
// perform reading operation;

In the open function of fstream class, second argument is the file opening mode. The
mode ios::in is for reading only and ios::out for writing only. The modes are defined as
enumeration constants in the class ios so scope resolution operator is used with it. We discuss
more modes later.

Note that there is no ios::in or ios::out default mode for fstream objects. You must
specify both modes if your fstream object read and write files. We can also have constructor
method of fstream for creating and opening a file as

fstream file(“num.txt”,ios::in);
char str[10];
file>>str;
cout<<str<<endl;
Let‟s have some programming examples first then we will see what other modes we can
have for handling the files.

Program : 12.1 Demo of file handling, writing to file ver

#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream fobj(”demo.txt”);
fobj<<”File Handling Demo\n”;
fobj.close();
}

OUTPUT:
(Blank Screen)

Explanation:
The statement ofstream fobj(“demo.txt”); creates an object of ostream
class type named fobj and passes file name as “demo.txt”. This way of creating file is
called constructor notation as we are creating an object of ostream type by calling the
constructor which takes an arguments of type char* type. After the execution of the
above statement a file stream fobj is created and linked to the file “demo.txt”. Now when
you want to the file you can write it as shown with the use of<<operator.

fobj<<”File handling demo\n”;

This writes string “File Handling demo” to the file “demo.txt”.


Note ofstream class is meant only for writing to the disk files. You cannot read from the file
using an object of ofstream. As soon as you open the file using an object of ofstream class type.
The file is automatically opend in the write mode. That‟s why no mode was specified while
opening the file. If file “demo.txt” were already existing its contents will be destroyed and file
pointer will be placed at the beginning of the file. If file where not already present it will be
created.

 
- 128 -
Ideal C++

Program 12.2 : Demo of file handling, writing to file, version 2.

#include<iostream.h>
#include<fstream.h>
void main()
{
ostream fobj;
fobj.open(“demo.txt”);
fobj<<”File handling demo\n”;
fobj.close();
}

OUTPUT:
(Blank Scree)

Explanation : The program shows the other method of opening a file for writing only. It
simply creates an object of ofstream class type and by using open method open the file. Rest is
same as explained in the previous program. There is one more parameter to the open method
which specifies the mode in which we want to open the file. Here mode for writing is ios::out,
but this is optional for ofstream class as by default file is opened for writing only.

Program 12.3 : Demo of file handling, reading from file.

#include<iostream.h>
#include<fstream.h>
void main()
{
ifstream obj;
fobj.open(“demo.txt”);
char str[30];
fobj.getline(str,30);
cout<<”string read from file\n”;
cout<<str<<endl;
fobj.close();
}

OUTPUT:
String read from file
File handling demo

Explanation : The statement ifstream fobj; creates an object of istream type name fobj
The class ifstream is meant only for reading only. We open the file using the open method. The
file name which we want to open is passed as argument to open method. The open method open
the file demo.txt and links object fobj to this file. Now this object fobj work as a stream for
reading from this file “demo.txt”. We read from the file as:

fobj.getline(str,30);
The above line reads from the file “demo.txt” first 29 characters or number of character
till „\n‟ is not encountered. The scanned string is stored in str which we display on to the screen
using standard output stream cout.

Note the following two line


ifstream fobj;
fobj.open(“demo.txt”);
can be written as
ifstream fobj(“demo.txt”);

 
- 129 -
Ideal C++

as we did for ofstream class.

There is one more parameter to the open method which specifies the mode in which we
want to open the file. Here mode for reading is ios::in, but this is optional for ifstream class as by
default file is opened for reading only.

Program 12.4 : Writing person data to file.

#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream fobj;
fobj.open(“demo.txt”);
char name[20];
int age;
char gender;
cout<< “Enter the name\n”;
cin.getline(name,20);
cout<< “Enter the age and gender\n”;
cin>>age>>gender;
fobj<<name<<endl
<<age<<endl
<<gender<<endl
fobj.colose();
}

OUTPUT:
Enter the name
Namit
Enter the age and sex
21 F

Explanation : In the program we have opened a file demo.txt. in the file we are putting
the details of person viz : name,age and sex. We take from the standard input stream (i.e. from
keyboard) and put the scanned data to the file demo.txt which is linked to the fobj an object of
ofstream class type. Note after each data item put into the class, a new line is inserted. This
comes handy when we read data from the file.

Program 12.5 : Reading Person data from file.


#include<iostream.h>
#include<fstream.h>
void main()
{
ifstream fobj;
fobj.open(“demo.txt”);
char name[20];
int age;
char gender;
fobj.getline(name,20);
fobj>>age>>gender;
cout<<”Name=”<<name
<<”\nAge=”<<age
<<”\ngender=”<<gender<<endl;
fobj.close();
}
OUTPUT:
Name=Namit
Age=21
gender=F

 
- 130 -
Ideal C++

Explanation : here we opened the file which we created in the previous program. We
create three variable: name,age and sex. The file is opened in read mode using object of istream
type named fobj. When fobj.getline(name,20); it reads more from the file demo.txt. After that are
and sex are read from the file in the next statement as:
fobj>>age>>gender;
This is similar to reading from keyboard using cin but here instead of reading
from keyboard we are reading from file.

12.4 File Opening Modes

S.N Mode Meaning


1. ios::in Opening file in read mode only
2. ios::out Opening file in write mode only
3. ios::app Opening file in append mode
4. ios::trune File contents deleted if file already exists
5. ios::nocreate In case file does not exist, open function will fail
6. ios::noreplace Opens the file if file already exists
7. ios::binary Open binary file
8. ios::ate File pointer move to end of file an opening the file

A Brief description of all the modes is as follows:


(1) ios::trune If the file already exists, its contents are discarded. This mode is implied
if ios::out is specified, and ios::ate, ios::app, and ios::in are not
specified.

(2) ios::noreplace If the file already exists, the function fails, This mode automatically
opens the file for writing if file does not exist.

(3) ios::binary opens the file in binary mode (the default is text mode);

(4) ios::in The file is opened for input. The original file (if is exists) will not be
truncated.

(5) ios::ate The function performs a seek to the end of file. When the first new byte
is written to the file, it is appended to the end, but when
subsequent bytes are written, they are written, they are written
to the current position i.e. anywhere in the file.

(6) ios::app The function performs a seek to the end of file. When new bytes are
written to the file, they are always appended to the end, even
if the position is moved the ostream::seekp function.

(7) ios::nocreate It the file does not already exits, the function fails.

(8) A file can be opened in more than one mode, number of modes can be
combined using binary OR symbol (|) as
file.open(“demo.txt”,ios::in|ios::out|ios::binary):

 
- 131 -
Ideal C++

12.5 PROGRAMMING EXAMPLES

Program 12.6 Reading and writing the same file in one program

#include<iostream.h>
#include<fstream.h>
void main()
{
fstream rw;
rw.open(“demo1.txt”, ios::out);
char str[50];
cout<<” Enter a string\n”;
cin.getline(str,50);
rw<<str<<endl;
rw.close();
rw.open(“demo1.txt”, ios::in);
rw.getline(str,50);
cout<<”string read from file\n”;
cout<<str<<endl;
rw.close();
}
OUTPUT:
Enter a string
Naughty Nanny
String read from file
Naughty Nanny

Explanation : Using an object of fstream class we can open the file in both the mode read and
write using function open. Initially the file is opened in write mode as
rw.open(“demo1.txt”,ios::out);

The second parameter is file opening flag. The ios is a class and out is the property of the
class, Togeher they are written as ios::out which indicated that we have opened the file demo.txt
in write mode. Again if file did not exist already it will be carated. If already created then all the
contents will be wiped off. A string is taken from the standard input stram and written to the file
as rw<<str<<endl;
File is then closed by calling close method as
rw.clsoe();

The file closing clears all buffers related to the file dem1.txt and unlinks file demo1.txt
from fstream object rw. The file closing is must as pointer advances into the file as characters are
written to it so after entering string str to th file pointer will be advanced by sizeof(str) bytes. To
get the pointer beginning to the file and opening it back in reading modre file closing is must.
To read from the file what we have entered just now we open the file agagin. But this
time in read mode with the help of flag ios::in. This flag open the file demo1.txt in read mode.
We read the string from the file by written
rw.getline(str,50);

Which reads stirng from file pointer by rw and stores the string in str. The read string is
displayed back to the screen using standard output stream cout.

 
- 132 -
Ideal C++

Program 12.7: Reading and writing the same file in one program

#include<iostream.h>
#include<fstream.h>
void main()
{
Fstream rw;
rw.open(“demo1.txt”,ios::out|ios::in);
char str[50];
rw<<str<<endl;
rw seekg(0 ios ::beg);
rw.getline(str,50);
cout<< “String read from file\n”;
cout<<str<<endl;
rw.close();
}

12.6 Checking end of file


When file is opened for reading, data from file can be read as long as file is open and till
end of file is not encountered. We open the file in read mode and read mobile details from the
file which is displayed on to the scree.

(a) In the first method the file stream object can be written in the while loop as
while (filestr)
{
read from file pointer by filestr;
process data;
}

As long as we are reading filestr returns nonzero value. As soon as end of file is encountered,
filestr returns zero while loop terminate.

(b) The second method which is most frequently used is of finding end of file is
using eof() function. The function eof returns zero as soon as
there is some data in the file i.e. as long as end of file is not
reached. As soon as end of file is reached, eof funcjtion returns
nonzero value. It can be used with while loop as

while(filestr.eof ( ) = =0) or while(!file.eof( ))


{
read from file pointer by filestr;
process data;
}

Program 12.9 Demo of eof function and append mode.

#include<iostream.h>
#include<fstream.h>
void main( )
{
fstream rw;
char str[5];
rw.open(“demo.txt”,ios ::in);
cout<<”data read from file\n”;
while(rw.eof()==0)

 
- 133 -
Ideal C++

{
rw.getline(str,50);
cout<<str<<endl;
}
rw.close( );

rw.open(“demo.txt”,ios ::app);
cout<<” Enter a string to append\n”;
cin.getline(str,50);
rw<<<str<<endl;
rw.close( );
rw.open(“demo.txt”,ios ::in);
cout<< “File with appended data\n”;
while(rw.eof( )==0)
{
rw.getline(str,50);
cout<<str<<endl;
}
rw.close( );
}

OUTPUT:
data read from file
c++ programming
is really
fun
Enter a string to append
Increasing day by day.
File with appended data
C++ programming
is really
fun
increasing day by day

Explanation: The file demo.txt is initially opened in read mode. The function eof
returns 0 as long as we are reading from file. As soon as end of file is reached. Function eof
returns a non zero value. We read from the file till function eof returns 0 . In each iteration of
the while loop we read a string str of maximum 49 character. As soon as end of file is
encountered while loop terminates. We close the file and open in the append mode by using
ios::app flag. When file is opened in append mode. File pointer is at the end of the file. The
string to be appended to the file is taken from user and appended to the file. File is closed again.
Next file is opened in read mode and is displayed which shows appended string together with the
original contents before appending.

Program 12.10 Reading and writing using get and put.


#include<iostream.h>
#include<fstream.h>
void main()
{
fstream rw;
char ch;
rw.open(“temo.txt”,ios ::in|ios ::out);
cout<< “enter some data\n”;
cin.get(ch);
while(ch!=EOF)
{
rw put(ch);
cin.get(ch);
}

 
- 134 -
Ideal C++

rw.seekg( 0 ,ios::beg);
while(rw.eof( ) = =0)
{
cout.put(ch);
rw.get(ch);
}

rw.close();
}
OUTPUT:
Enter some data
Heart Beat (Enter F6 or ctrl-z)
Heart Beat

Explanation : The two functions put and get allows us to write and read file sequentialiy. We
open the file temp.txt for both reading and writing. We prompt user to enter some data. The
data is scanned character by character using get and put into the file one character at a time.
When user enter F6 or ctrl-z, first while loop terminates. The pointer is ten moved to beginning
of the file by writing rw.seekg(0,ios::beg). We now read from file character by character till end
of file does not reach. EOF is a macro defined in the file stdio.h whose ASCII value in 26.

Program 12.11 File Copying using get and put.

#include<iostream.h>
#include<fstream.h>
void main())
{
` fstream source, dest;
char sfile[15], dfile[15];
char ch;
cout<< “Enter the source file name\n”;
cin>>sfile;
source.open(sfile,ios::in);
cout<< “Enter the destination file name\n”;
cin>>dfile;
dest.open(dfile,ios::out);
while(source.eof( ) ==0)
{
source.get(ch);
dest.put(ch);
}
source.close( );
dest.close();
}
OUTPUT:
Enter the source file name
demo.txt
Enter the destination file name
df.txt

Explanation: We input source and destination file name from the user. It is assumed
that source file exits so we have not put any error checking code in the program. The source file
is than opened in read mode and destination file is in write mode. We read one character at a
time from source file and put this into destination file. This continues till source file does not
come to end. In the end both files are closed.

 
- 135 -
Ideal C++

Program 12.12 Working with two files at a time.


#include<iostream.h>
#include<fstream.h>
void main( )
{
fstream f1,f2;
f1.open(“name.txt”,ios ::out);
f1<< “Kriti\n”;
f1<< “Rinki\n”;
f1<< “chhaya\n”;
f1.close( );
f2.open(“sname.txt”,ios ::out);
f2<< “Jain\n”;
f2<< “Sharma\n”;
f2<< “Goyal\n”;
f2.close( );
f1.open(“names.txt”, ios::in);
f2.open(“snames.txt”,ios::in);
char str[15];
while(f1.eof( ) = = 0)
{
f1.getline(str,15);
cout<<str<< “ ”;
f2.getline(str,15);
cout<<str<<endl;
}
f1.close();
f2.close();
}
OUTPUT:
Kriti Jain
Rinki Sharma
Chaaya Goyal

Explanation: In the program we have used two files name.txt in which we have stored few
names and sname.txt in which we have stroed surnames. We open the two files simultaneously
and display the full name. If end of first is enconterd we terminate the program.

Program 12.13 Counting Number of Charcters in File


#include<iostream.h>
#include<fstream.h>
void main()
{
fstream rw;
char str[5];
int count=0;

char ch;
rw.open(“demo1.txt”,ios ::in);
cout<< “Data read from file\n”;
rw.get(ch);
while(rw.eof( ) = =0)
{
cout.put(ch);
rw.get(ch);
count++;
}

cout<< “number of character in file=“<<count<<endl;


rw.close();
}

 
- 136 -
Ideal C++

OUTPUT:
data read from file
namit
21
F
Appended
Number of character in file=20

Explanation: The program opens the file demo1.txt in read mode. It reads file character by
character and increments count in each iteration. Out of while loop, cout displays number of
character in the file. Note you have to add 4 extra for new line characters if you counter check
the coutput by finding number of characters manually.

12.7 Random Access in File

Random Access means reading data randomly from any where in the file. For this purpose we
need to set the position of the file pointer first in the file and then read the data. C++ file stream
classes provide the following for the manipulation of file pointer any where in the file. With the
help of these functions we can access data in a random fashion.
(a) seekg
(b) seekp()
(c) tellg()
(d) tellp()

The function seekg and tellg are used when we are reading from file i.e. when used with the get
pointer that‟s why the suffix g. The functions tellp and seekp are used when writing to the file i.e.
when put pointer is used that‟s why the suffix p. The seek(p/g) function moves pointer to the
specified position and tell(p/g) gives the position of the current pointer. The most frequently
used function is seekg whose syntax as:

istream& seekg( streamoff off, ios ::seek_dir dir);


The off is the new offset value and streamoff is a typedef equivalent to long, offset
positive means move forwards, -ve means move backwards and 0 means stay at the current
position. First byte in the file is at position 0. The dir is the seek direction. Must be one of the
following enumerators:
 ios::begSeek from the beginning of the stream.
 ios::cur Seek from the current position in the stream.
 ios::endSeek from the end of the stream.

Few examples given below:

ifstream file;
file.seekg(2,ios ::beg)-> Third byte from beginning.
file.seekg(6,ios ::cur)-> Forward by 6 bytes from current pos.
file.seekg(-5,ios::cur)-> Background by 5 byte from current pos.
file.seekg(-4,ios::end)->Backward by 4 bytes from end.
file.seekg(0,ios ::cur)->Stay at the current position.

Similar to seekg you can use seekp for moving pointer within a file which is opened for
writing. File and moving pointer to the end of the file. They can be used as:

 
- 137 -
Ideal C++

ofstream file(“num.txt”,ios ::ate);


cout<<file.tellp<<endl;

When file is opened the pointer will be at the end of the file and teelp will give number
of bytes in the file. Similarly we can use tellg as:

ifstream file(“num.txt”,ios ::in);


file.seekg(0,ios ::end);
cout<<file.tellg( )<<endl;

when file is opened for reading; the file pointer will be in the beginning of the file so we
have moved pointer to the end of the file using seekg.

Let‟s have few program now which uses these function.

Program 12.4 Reversing File Contents.


#include<iostream.h>
#include<fstream.h>
void main( )
{
fstream file;
int count,x=1;
char ch;
file.open(“num.txt”,ios
cout<<”File Contents\n”;
while(file.eof( )= =0)
{
file.get(ch);
cout.put(ch);
}

cout<<”\n Reverse contents\n”;


file.clear( ) ;
file.seekg(0,ios ::end);
count=file.tellg( );
while(x<=count)
{
file.seekg(-x,ios ::end);
file.get(ch);
cout.put(ch);
x++;
}
cout<<endl;
file.close( );
OUTPUT:
File contents
Love is blind
I love programming
Reverse contents
Gnimmargorp evol I
Dnilb si evoL

Explanation: Initially file is opened in the read mode and displayed. The file then
reaches at the end of file and end of file error bit is set. It is must to clear this end of file bit
other wise after setting the pointer to last character of the file we won‟t be able to read from file.
Number of characters in the file is then find out as

 
- 138 -
Ideal C++

file.seekg(0,ios ::end);
count=file.tellg( );

Now to display reverse contents of the file we start from 1 and continue till x<=count. We read
first character from end when x=1 as
file.seekg(-x,ios::end);
file.get(ch);

Which is displayed using cout.put(ch). As x increments we have the second character and so on.

Program 12.15 : Random access demo, printing name “Pari”.

#include<iostream.h>
#include<fstream.h>
void main( )
{
fstream file;
char ch;
file.open( “alpha.txt”,ios ::out);
file<< “ABCDEFGHIJKLMNOPQRSTUVWXYZ\n”;
file.close();
file.open(“alpha.txt”,ios::in);
// first character is at 0 pos
// 16th byte from beginning
file.seekg(15,ios ::beg);
file.get(ch);
cout<<ch; //prints P
// first character from beg
file.seekg(0,ios ::beg);
file.get(ch);
cout<<ch; //prints A
// 11th character from current position
// including current pos „I‟
file.seekg(-10,ios::cur);
file.get(ch);
cout<<ch; //prints
cout<<endl;
file.close();
}
OUTPUT:
PARI

Explanation: The program is quite self-explanatory as comments are inserted at appropriate


places. When you place \n inside the file as this is done in the program then start counting z
from -3 position else count zfrom position -1 (remove \n);

Program 12.16: Counting lines and character

#include<iostream.h>
#include<fstream.h>
void main()
{
fstream file;
int lines=0, count=0;
char ch;
file.open(“temp.txt”,ios::out);

 
- 139 -
Ideal C++

cout<<” enter some text\n”;


cin.get(ch);

while(ch!=EOF)
{
file.put(ch);
cin.get(ch);
}
file.close( );
file.open(“temp.txt”,ios::in);
while(file.eof()==0)
{
file.get(ch);
if(ch==‟\n‟)
lines++;
count++;
}
cout<<”Number of Characters=”<<count-lines-1<<endl;
cout<<”Number of lines=”<<lines<<endl;
file.close( );
}
OUTPUT:
Enter some text
one
two
three
four
Number of characters=15
Nuber of lines=4

Explanation: For Counting number of lines we check for „\n‟ and for counting number of
characters we count all characters in while by increamenting count in each iteration. In the end
when while loop terminates cout will be one more than total number of character. It also includes
number of „\n‟ characters. So in the end number of characters is displayed as count-line-1.

Program 12.17 Demo of ios::nocrete flag.


#include<iostream.h>
#include<fstream.h>
void main()
{
fstream file;
file.open(“silly”,ios ::nocreate);
if(file.fail())
{
cout<<”File Opening error\n”;
exit(0);
}
}
OUTPUT:
File opening error

Explanation: We have assumed that file silly does not exist. The ios::nocreate does not
open the file if it already not existing and instead gives error. The error in opening is checked
using file.fail() which returns true if there is some error in opening the file. As file does not exist
if condition is true so cout displays Fil opening error and program terminates.

 
- 140 -
Ideal C++

Program 12.18 Reading and writing numeric data.

#include<iostream.h>
#include<fstream.h>
void main()
{
int i;
ofstream file(“num.txt”);
for(i=1;i<=10;i++)
cout<<i<<endl;
file.close( );
ifstream file1(“num.txt”);
while(1)
{
file>>i;
if(file.eof( )!=0)
break;
cout<<i<<endl;
}
file1.close( );
}
OUTPUT:
1
2
3
4
5
6
7
8
9
10

Explanation: The program is simple. We input 10 number into the file and later display it back.
Not there is no special function available in C++ for handling numbers using file.

WORKING WITH BINARY MODES


Numeric data including integer and floating point as well as character data, all are treated in
terms of character data i.e. string “file” will take 4 bytes in memory, integer number 1245 will tae
4 byte in memory and even 1.23 will take 4 bytes in memory. But as these data stroed in disk file
they are stored in binary form and in this they are stored as per their type i.e. integer takes 2
bytes, float file and it contains lots of numberical data it will require large amount of disk space.
For that can have two functions provided by C++ stream class read and write which reads and
write data in terms of binary. For Opening file in binary mode we have the mode ios::binary. The
prototype of both the functions is given as

ostream& write(const char* pch, int nCount);


istream& read(char* pch, int nCount);

The first argument in the write is the address of the character array and second is the
number of charaters to be written. Similar arguments apply to fread with the differene that it
reads instead of writing.

Program 12.24 Reading and writing object.


#include<iostream.h>
#include<fstream.h>
#include<string.h>

 
- 141 -
Ideal C++

class person
{
char name[10];
int age;
public:
void input(char n[], int a)
{
strcpy(name,n);
age=a;
}

void show( )
{
cout<<”Name=”<<name<<endl;
cout<<”Age=”<<age<<endl;
}
};
void main( )
{
fstream file;
file.open(“obj.txt”,ios ::in|ios ::out);
person d;
d.input(“Manav”,21);
file.write((char*) &d,sizeof(d));
file.read((char*) &d,sizeof(d));
d.show( );
file.close( );
}
OUTPUT:
Name=Manav
Age=21

Explanation: The two functions write and rad work with binary files. Initially we assign values to data
members of object d using function input. We then call function write which takes first arguments as
address of object d, i.o. where the write has to perform and second takes size of object. After writing
object to the file, reading, takes place by read function whose syntax is similar to the write. The object is
read and displayed using a call to function show.

Program 12.25 Reading and witing object.


#include<iostream.h>
#include<fstream.h>
#includde<string.h>
class person
{
char name[10];
int age;
char sex;
public:
void input( )
{
cout<<”Enter person name\n”;
cin>>name;
cout<<” Enter age and sex”;
cin>>age>>sex;
}
void show( )
{
cout<<”Name=”<<name<<endl;
cout<<”Age=”<<age<<endl;
cout<<”Sex=”<<sex<<endl;
}
};

 
- 142 -
Ideal C++

void main( )
{
fstream file;
file.open(“obj.txt”,ios ::in|ios ::out);
person d[3];
int i;
for(i=0;i<3;i++)
{
d[i].input( );
file.write((char*) &d[i],sizeof(d[i]));
}

cout<<”Data read from file\n”;


for(i=0;i<3;i++)
{
cout<<”\n Person “<<i+1<<”\n”;
file.read((char*) &d[i],sizeof(d[i]));
d[i].show( );
}

file.close( );
}

OUTPUT:
Enter person name
namit
Enter age and sex
21 F
Enter person name
Koyal
Enter age and sex
19 F
Enter person name
Akshay
Enter age and sex
20 M
Data read from file
Person 1
Name=namit
Age=21
Sex=F
Person 2
Name=Koyal
Age=19
Sex=F
Person 3
Name=Akshay
Age=20
Sex=M

Explanation: In the program we have an array of objects d of size 3 of class person


type. We run for loop and take values for data members for all three objects using function input
The objects are then stored in the file using function read. In the next for loop we read objects
from file and display using write.

 
- 143 -
Ideal C++

Program 12.26 reading and writing


#include<fstream.h>
void main( )
{
fstream file;
int a[10],i;
file.open(“arr.txt”,ios ::in|ios ::out);
for(i=0;i<10;i++)
a[i]=i+1;
file.write((char*)a,sizeof(a));
for(i=0;i<=9;i++)
a[i]=0;
file.seekg( 0,ios::beg);
file.read((char*)a,sizeof(a));
cout<<”Array is\n”;
for(i=0;i<=9;i++)
cout<<” “<<a[i];
cout<<endl;
file.close( );
}
OUTPUT:
Array is
1 2 3 4 5 6 7 8 9 10

Explanation: Not only objects we can also store array into the file. In the program we have first
assigned numbers 1 to 10 into the array a and stored the whole array into the file arr.txt by using
just one statement file.write((char*)a,sizeof(a)); a is the base address of the array, sizeof a gives
40. We thaen make all elements to array a to zero so that when we read back from file we get the
original array. The array is read through fread and displayed.

Program 12.27 Student Data Base Management.

#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
#include<stdio.h>
class student
{
char sname[15];
int c_rno;
char cls[10];
public:
void input_data( );
void show_data( );
int getcrn ( )
{
return c_rno;
}
};
void student ::input_data( )
{
cout<<”Enter the student name\n”;
cin>>sname;
cout<<”Enter college roll no and class \n”;
cin>>c_rno>>cls;
}
void student ::show_data( )
{
cout<<”Name=”<<sname<<”\t”;
cout<<”CRN=<<c_rno<<”\t”;

 
- 144 -
Ideal C++

cout<<”Class=”<<cls<<endl;
}

void main( )
{
int ch,crn;
student st;
fstream file;
int found=0;
int noc,nor;
long int move;
file.open(“student.txt”,ios ::in|ios:: out|ios :binary|ios ::ate);
do
{
cout<<”\n Welcome to Student Database\n”;
cout<<”1. Add a record\n”;
cout<<”2. View records\n”;
cout<<”3. Search a record\n”;
cout<<”4. Delete a record\n”;
cout<<”5. Modify a record\n”;
cout<<”6. Count records\n”;
cout<<7. Exit\n”;

cout<<”Enter your choice (1 to 6) \n”;


cin>>ch;
switch(ch)
{
case 1: st.input data();
file.write((char*)&st,sizeof(st));
cout<<”Record is added\n”;
file.clear( );
break;

case 2: file.seekg(0,ios ::beg);


while(file.read((char*) &st,sizeof(st));
st.show_data( );
break;
case 3: cout<<”Enter the college roll number\n”;
cin>>crn;
while(file.read((char*)&st,sizeof(st)))
{
if(st.getcrn( )==crn)
{
cout<<”Record found\n”;
st.show data( );
found=1;
}
}
if(found= =0)
cout<<”Record does not found\n”;
file.clear( );
break;
case 4: cout<<”Enter the college roll number\n”;
cin>>crn;
file.seekg(0,ios ::beg);
while(file.read((char*)&st,sizeof(st)))
{
if(st.getcrn( ) ==crn)
{
cout<<”Record Found\n”;
found=1;
st.show data( );

 
- 145 -
Ideal C++

int tans;

cout<<”Are you sure to delete this record (1/0\n”;


cin>>ans;
if(ans==1)
{
fstream newf;
newf.open(“newstu.txt”,ios ::out);
while(file.read((char*)&st,sizeof(st)))
{
if(st.getcrn( )!=crn)
newf.write((char*)&st,sizeof(st));
}
file.close( );
remove(“student.txt”);
newf.close( );
rename(“newstu.txt”,”student.txt”);
file.open(“student”,ios ::in|ios ::out|ios::binary|ios ::ate);
cout<<”Record deleted\n”;
}
}
}
if(found= =0)
cout<<”Record does not found\n”;
file.clear( );

cout<<”Enter the record number to modify\n”;


int recno;
cin>>recno;
move=(recno-1)*sizeof(st);
file.seekg(move,ios ::beg);
cout<<”Pls enter new data\n”;
st.input_data( );
file.write((char*)&st,sizeof(st));
file.clear( );
break;
case 6: file.seekg(0,ios ::end);
noc=file.tellg( );
nor=noc/sizeof(st);
cout<<”Number of records=”<<nor<<endl;
break;
case 7: cout<<”Bye Bye\n”;
exit(0);
}
}while(ch>=1 && ch<=7);
}
OUTPUT:
Welcome to Student Database
1. Add a record
2. View records
3. Search a records
4. Delete a record
5. Modify a record
6. Count records
7. Exit
Enter your choice(1 to 6)
1
Enter the student name
namit
Enter college roll no and class
101 viisem
Record is addes
Welcome to Student Database

 
- 146 -
Ideal C++

1. Add a record
2. View records
3. Search a record
4. Delete a record
5. Modify a record
6. Count records
7. Exit
Enter your choice (1 to 6)
1
Enter the student name
harsh
Enter college roll no and class
202 vsem
Record is added
Welcome to student Database
1. Add a record
2. View records
3. Search a record
4. Delete a record
5. Modify a record
6. Count records
7. Exit
Enter your choice (1 to 6)
2
Name=namit CRN=101 Class=viisem
Name=harsh CRN=202 Class=vsem
Welcome to Stuetn Database
1. Add a record
2. View a records
3. Search a record
4. Delete a record
5. Modify a record
6. Count records
7. Exit
Enter your choice (1 to 6)
1
Enter the student name
purv1
Enter college roll no and class
123 viisem
Record is added
Welcome to Student Database
1. Add a record
2. View records
3. Search a record
4. Delete a record
5. Modify a record
6. Count records
7. Exit
Enter your choice (1 to 6)
6
Number of records=3
Welcome to Student Database
1. Add a record
2. View record
3. Search a record
4. Delete a record
5. Modify a record
6. Count records
7. Exit
Enter your choice (1 to 6)
7
Bye Bye

 
- 147 -
Ideal C++

Explanation: To modify a record we initially reach to the location of that record. The location can
be found out as
loc(n-1) * sizeof(st);

Where st is an object of class student and n is the record number. Then through seekg we reach to
the loc in the file i.e. beginning of the record which is to be modified. We then accept the new data
for the record and overwrite the existing record.
The file is opened in ios::ate mode which takes pointer to the end of the file. For moving
any where in the file we have to use seekg. For accessing file again once end of file has been se
we have cleared it by using clear function which turn off the end of fil flag.
To search for a record we ask from the user the college roll no and scan the whole file for
the record where c_rno matches with the user supplied crn As c_rno is private so we have a public
member function getcrn which gives college roll number.
For deletion of a record we move all the other records to a temporary file temp.txt. We
then remove the original file using in built function remove which takes a single argument of const
char* type, the file name to be removed. We then rename the temporary file temp.txt to the old
student.txt.

12.11 Error Handling


When dealing with the files error might occurs such as file does not exist, reading from
file which is opened for writing only, path is not valid, file already exist, etc. To cope up with all
these errors we must check whether the file is opened successfully or what type of error has been
generated. Some of the error handling function with fheir description is given below:

1. The good function:


syntax : int good( ) const;
Returns nonzero values if all error bits are clear. Note that the good member function is
not simply the inverse of the bad function.

2. The bad function


syntax : int bad( ) const;
Return a nonzero value to indicate a serious I/O Error. This is the same as setting the
badbit error state. Do not continue I/O operations on the stream in this situation.

3. The fail function


syntax : int fail( ) const;
Return a nonzero value if any I/O error (not end of file) has occurred. This condition
corresponds to either the badbit or failbit error flag being set. If a call to bad return 0,
you can assume that the error condition is nonfatal and that you can probably continue
processing after you clear the flags.

4. The clear function


syntax : void clear(int nState = 0);
The parameter nState, if 0, then all error bits are cleard; otherwise bits are set according
to the following masks (ios enumerators) that can be combined using the bitwise OR( | )
Operator. The nState parameter must have one of the following values:
 ios::goodbit No eoor condition (no bits get);
 ios::eofbit End of file reached.
 ios::failbit A possibly recoverable formatting or conversion error.
 ios::badbit A severe I/O error.
The function sets or clears the error-state flags. The rdstate function can be
used to read the current error state.

 
- 148 -
Ideal C++

5. The eof function:


syntax : int eof( ) const;
Returns a nonzero value if end of file has been reached. This is the same as setting the
eofbit error flag.

6. The rdstate function:


syntax : int rdstate( ) const;
Returns the current error state as specified by the following masks (ios enumerators):
 ios::goodbit No error condition.,
 ios::eofbit End of file reached.
 ios::failbit A possibly recoverable formatting or conversion error.
 ios::badbit severe I/O eoor or unknown state.
This is shown in the figure given below. The last 4 bits are unused.

The returned value can be tested against a mask with the AND (&) Operator. But we do
not have to as we can hva functions which tells us which bit is set or reset.

7 6 5 4 3 2 1 0

goodbit badbit failbit eofbit

Program : 12.28 Error Handling with files


#include<fstream.h>
void main( )
{
ofstream file(“silly.txt”,ios ::noreplace);
if(!file)
{
cout<<”File Opening Error\n”;
}
cout<<”The various flags set/reset are\n”;
cout<<”rdstate=”<<file.rdstate( )<<endl;
cout<<”bad=”<<file.bad( )endl;
cout<<”fail=”<<file.fail( )<<endl;
cout<<”good=”<<file.good( )<<endl;
cout<<”eof=”<<file.eof( )<<endl;
}
OUTPUT:
File opening Error
The various flags set/reset are
rdstate=2
bad=0
fail=2
good=0
eof=0

Explanation: The file silly.txt was existing earlier. The noreplace flashes error if file was
existing and we tried to open it for writing. That is using this flag we come to know that file
already exist and we do not have to modify the file. The file opening error occurred so fail will
return a nonzero value, good returns 1 only when no error of any type occurs i.e. all the bits are
cleard. The bad returns 0 as there is no I/O error. Eof was not reached so eof returns 0. Now
checking from the figure the rdstate will be as:

 
- 149 -
Ideal C++

0 0 1 0

0010 is decimal 2, so rdstate returns 2.


In the program if file was not epened and we try to write to the file then function bad returns
true and badbit is set which indicates file input/output error. This can be checked again as

file<<”Writing to the file\n”;


if(!file)
{
cout<<Writing error\n”;
}
// check all flags here:

Program 12.29 Demo of fail and good.

#include<fstream.h>
void main( )
{
ifstream file(“num.txt”,ios ::nocreate);
if(file.good( ))
{
cout<<”File is opened successfully\n”;
cout<<”good flag=”<<file.good( )<<endl;
}
else if(file.fail( ))
{
cout<<”Error in opening file\n”;
cout<<”fail flag=”<<file.bad( )>>endl;
}
}

OUTPUT:
(Assume file does not exist)
Error in opening file
fail flag=0
(Assume file does exist)
File is opened successfully
good flag=1
Explanation: The program is self-explanatory.

 
- 150 -

You might also like