Sei sulla pagina 1di 152

OOPs and Basics of C++

Need of C++
During the late 1970s and early 1980s, C became the Leading computer programming language, and it is
still widely used today. Since C is a successful and useful language, what is the need of C++?
Throughout the history of programming, the increasing complexity of program has driven the need for
better ways to mange that complexity. C++ is a response to that need.
Approaches to programming have changed dramatically since the invention of the computer. For example,
when computers were first invented, programming was done by manually toggling in the binary machine
instructions by use of the front panel. As long as programs were just a few hundred instructions long, this
approach worked. As programs grew, assembly language was invented so that a programmer could deal
with larger, increasingly complex programs by using symbolic representations of the machine instructions,
As programs continued to grow, high-level languages were introduced that gave the programmer more
tools with capabilities to handle complexity.
The first widespread language was, of course, FORTRAN. While FORTRAN was an impressive first
step, it is hardly a language that encourages clear and easy-to-understand programs. The 1960s gave
birth of structured programming. This is the method of programming championed by languages such as C.
The use of structure languages enables programmers to write, for the first time, moderately complex
programs fairly easily. However, even with structured programming methods, once a project reaches a
certain size, its complexity exceeds what programmers can mange. By the early 1980s, many projects
were pushing the structured approach past it limits. To solve this problem a new way to program was
invented, called Object-OrientedProgramming (OOP). Object-oriented programming is discussed in
detail later in this book, but here is a brief definition: OOP is a programming methodology that helps
organize complex programs through the use of inheritance, encapsulation and polymorphism.
In the final analysis, although C is one of the worlds great programming languages, there is a limit to its
ability to handle complexity. Once a program exceeds somewhere between 25,000 to 1,00,000 lines of
coed, it becomes so complex that is the difficult to grasp as a totality. C++ allows this barrier to be broken,
and helps programmer comprehend and mange larger programs.
Bjarne Stroustrup invented C++ in 1979, while he was working at Bell Laboratories in Murray Hill, New
Jersey. Stroustrup initially called the newly invented language as a C with Classes. However, in 1983,
the name was changed to C++. C++ extends C by adding object-oriented features. Because c++ is built

upon the foundation of C, it includes all Cs features, attributes and benefits. This is a crucial reason for
the success of C++ as a language. The invention of C++ was not an attempt to create a completely new
programming language. Instead, it was an enhancement to an already highly successful language C.
R As Discussed above C++ is superset of C. Therefore, almost all C programs are also C++
program.
The Three OOP Principles
All object-oriented programming languages provide mechanisms that help you implement the object-oriented
model. They are encapsulation, inheritance, and polymorphism. Lets take a look at these concepts now.
Encapsulation
Encapsulation is the mechanism that binds code and the data. It manipulates and keeps both safe from
outside interference and misuse. One way to think about encapsulation is a protective wrapper that prevents
the code and data from being arbitrarily accessed by other code defined outside the wrapper. Access to
the code and data inside the wrapper is tightly controlled through a well-defined interface. To relate this to
real world, consider the automatic transmission on an automobile. It encapsulates hundreds of bits of
information about your engine, such as how much you are accelerating, the pitch of the surface you are
on, and the position of the shift lever. You, as the user, have only one method of affecting this complex
encapsulation, by moving the gear-shift lever. You cant affect the transmission by using the turn signal or
windshield wipers, for example. Thus, the gear-shift lever is a well-defined (indeed, unique) interface to
the transmission. Further, what occurs inside the transmission does not affect objects outside the
transmission. For example, shifting gears does not turn on the headlights! Because an automatic transmission
is encapsulated, dozens of car manufactures can implement one in any way they please. However, from
the drivers point of view, they all work the same. This same idea can be applied to programming. The
power of encapsulated code is that everyone knows how to access it and thus can use it regardless of the
implementations details and without fear of unexpected side effects.
Inheritance
Inheritance is the process, which on object acquires the properties of another object. This is important
because it supports the concept of hierarchical classification. Inheritance is managed by hierarchical
approach (that is top-down approach) For example, classification of dog, which is turn is part of the
mammal class, which is under the larger class animal. Without the use of hierarchies, each object would
need to define all of its characteristics explicitly. However, by use of inheritance, an object need only
define those qualities that make it unique within its class. It can inherit its general attributes from its
parent. Thus, its is the inheritance mechanism that makes its possible for one object to be a specific
instance of a more general case. Lets take a closer at this process.
Most people naturally view the world as made up of objects that are related to each other in hierarchical
way, such as animals, mammals, and dogs. If you wanted to describe animals in an abstract way, you
would say they have some attributes, such as size, intelligence, and type of skeletal system. Animals also
have certain behavioral aspects; they eat, breath, and sleep. This description of attributes and behavior is
the class definition for animals.
2

If you wanted to describe a more specific class of animals, such as mammals, they would have more
specific attributes, such as type of teeth, and mammary glands. This is known as subclass of animals,
where animals are referred to as mammals super class.
Since mammals are simply more precisely specified animals, they inherit all of the attributes from animals.
A deeply inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.
Inheritance interacts with encapsulation as well. If a given class encapsulates some attributes, then any
subclass will have the same attributes plus any that it adds as part of its specialization. This is a key
concept, which lets object-oriented programs grow in complexity linearly rather than geometrically. A
new subclass inherits all of the attributes of all of its ancestors. It does not have unpredictable interactions
with the majority of the rest of the code in the system.
Polymorphism
Polymorphism (From the Greek, meaning many forms) is a feature that allows one interface to be used
for a general class of actions. The specific action is determined by the exact nature of the situation. Like
milk, is used to prepare Tea and one can make Coffee from it. Consider a stack. You might have a
program that requires three types of stacks. One stack is use for integer value, one for float value and

one for character. The algorithm that implements each stack is the same, even though the data being
stored differs. In non object-oriented programming , you would be required to create three different
sets of stack routines, with each set using different names. But in OOPs with the concept of polymorphism,
you can specify a general set of stack routines that all share the same names.
More generally, the concept of polymorphism is often expressed by the phrase one interface, multiple
methods. This means that is possible to design a generic interface to a group of related activities. This
helps reduce complexity by allowing the same interface to be used to specify a general class of action.
Its compiler job to select the specific action (that is method) as it applies to each situation. You need only
remember and utilized the general interface.
Extending the dog analogy, a dogs senesce of smell is polymorphic. If the dog smells a cat, it will bark
and run after it. If it smells food, it will salivate and run to its bowl. The same sense of smell is at work
in both situations. The difference is what is being smelled, that is, the type of data being operated upon by
the dogs nose!. This same general concept can be implemented in OOPs as it applies to methods.

Application of C++
C++ is very easy language for handling very large programs. While C++ is able to map the real-world
problem properly, the C part of C++ gives the language the ability to get close to the machine-level details.
C++ programs are easily maintainable and expandable. When a new feature needs to be implemented, it
is very easy to add to the existing structure of object.
3

First C++ Program


As early discussed (in C) the best way to learn a new programming language is writing a program in
it. Let us begin with a simple program, which prints Welcome to AZURE on the screen.
Example
/* First C++ Program */
#include<iostream.h>

// include header file

void main()
{ cout<<"Welcome to AZURE";
}
To write above program open Turbo C++ Editor, which is an integrated environment to compile and
execute the program.

Select New Option from the File menu to open Editor in Turbo C++ to write down above program,
which looks as per follows.

Key in above program and save it at proper place with .cpp extension.
To execute above program, Select Run option from Run menu or press Ctrl + F9 key combination.
The Compilation and linking process will be displayed in the progress window.
If there are any error(s) it will display all the respective error messages in message window otherwise you will get appropriate output.
Explanation of First C++ Program
Like C, The C++ program is a collection of functions. As C, when you run a C++ program,
the first statement is executed will be the beginning of a function called main(). The program may
consist more than one function, but execution of program is done from the function main(). The
word void preceding the function main() indicates that this particular function does not return any
value.
As you aware that every function in C returns value and by default it returns integer value. It is
true for C++. In C we can ignore return statement but in C++ its not possible. If you write
main() without specifying void, program should ends with return statement; otherwise a warning or
an error might occur.
# include directive causes the preprocessor to add the contents of the mention header file in the
program. iostream.h is responsible for the input and output for any program in C++. It contains
declarations for the identifier cout and the operator <<. So, it is necessary to include iostream.h
header file in the beginning of the program.
cout<<"Welcome to AZURE"; These output statement is used to display string or value of
variable on the screen. It is same as printf() function of the C language. We will discuss output
statement cout in details later on.
Comments are an important part of any program. They help the person writing the program and

anyone reading the program, to understand whats going on. These are non-executable statements
i.e. the compiler ignores comments. Comments are not compulsory in a program but inclusion of
comments in a program improves its readability. The comment used in C language ( /* */ ) for
single and multi-line are also valid in C++. // (double slash) symbol introduced for comment in
C++. A comment may start anywhere in the line and ends with end of lines. (There is no closing
symbol for //). It is also known as a single line comment.
Output in C++
In C++ cout is used to display string or value of variable on the screen. General form of cout is :
cout << String / Variable..;
cout (pronounced C out) is predefined object. (Object is a new terminology used in C++, we will
discuss it in detail later on), which represents the standard output stream in C++. A stream is an
abstraction that refers to a flow of data. Standard output stream represents the screen, although it
can be redirected to other output devices. (We will discuss it in details later on)
Here we have used insertion operator << with cout. The insertion operator inserts the String or
value of the variable on its right to the object on its left. << is also known as a put to operator. It
belongs in the category of cascading operator.
With << Operator we need not to specify the data type or its conversion character like printf()
function to display appropriate value. The insertion operator automatically assumes the data type of
the variable. One advantage of this is that user-defined data types can be used with this operator,
which was not possible with the printf() function.
Example
# include <iostream.h>
void main()
{
cout << "Hello World" << "\n" << "Welcome to AZURE";
}
We have used the insertion operator << repeatedly in the above program for printing result. The
multiple use of << in one statement is called cascading.
The Statement, cout << "Hello World" << "\n" << "Welcome to AZURE";
redirect the String Hello World to cout and then sends \n and Welcome to AZURE to cout
so that the Welcome to AZURE will print on a new line, \n is for new line.

R Leave necessary blank spaces for formatted output, when you use cascading
output operator.

Data Types
In any programming language data types allows a programmer to create variables for manipulate
various data in program.
C++ is a superset of C Language So, C++ supports all the data types (Basic & Derived) used in
C Language with its modifier. Following table list out all the basic data types and modifier along
with their size and range.
Data Type
integer (signed integer)
unsigned integer
short integer
short unsigned integer
long integer
long unsigned integer
float
double
long double
character
unsigned character

Bytes

Range

2
2
2
2
4
4
4
8
10
1
1

-32768 t0 32767
0 to 65535
-32768 t0 32767
0 to 65535
-2147483648 to +2147483647
0 to 4294967295
-3.4e+38 to +3.4e+38
-1.7e+308 to +1.7e+308
-3.4e+4932 to 1.1e4932
-128 to 127
0 to 255

C++ introduce new user-defined data type called class (We will discussed it very soon in detailed)
Variables
Variables plays important role in programming language. Values can be assigned to variables, which
can be changed during the execution of program.
In C Language variables must be declared before it appears in an executable statement and all the
variable must be declared before any executable statement of C in program or function. Declaration of variable after an executable statement is invalid in C. In C++ declaration of variable can
be done anywhere within the program or function - as and when they are required.
R Declaration and Initialization of the variable is same as C Language.
Example
#include<iostream.h>
void main()
{
cout << "Declaration of Variable any where in the program";
int i=10;

cout << "Value of i is : " << i;


float f=5.87;
cout << "Value of f is : " << f;
}
Operators in C++
C++ has a rich set of operators. Operators are the tools to manipulate data. An operator is a
symbol that represents some particular operation to be performed on the data value. All the different sets of operators used in C are valid in C++. In addition, C++ introduce some new operators.
We have already seen one of them namely insertion operator << and next topic introduce another
one called extraction operator >>.
Input in C++
In any computer programming language, program should accept values from a user to make it interactive and generalize. cin (pronounced C in) is responsible to get values from a user in C++. cin
is a predefined object that communicate to the standard input stream. By default Keyboard is treated
as a standard input stream. General form of cin is :
cin >> Variable;
Here we have used extraction operator >> with cin. It extracts the value from the keyboard and
assigns it to the variable on its right. >> is also known as a get from operator. It belongs in the
category of cascading operator.
R Like C Language, there is no need of conversion character with cin while you
accept value from a user.
Example
Accept character, number and name from a user.
#include<iostream.h>
void main()
{ char c;
int n;
char nm[];
cout<< "Entre Character" ;
cin >> c
cout<< "Entre Number";
cin >> n;
cout<< "Entre Name" ;
cin >> nm;
}

Example
Accept Number from a user and print its square in formatted manner.
#include<iostream.h>
void main()
{
int n,s;
cout<< "Entre Number";
cin >> n;
s = n * n ;
cout << "Square of " << n << "is " << s;
}
R One can use extraction operator >> repeatedly in the program i.e. extraction operator can be cascaded in the program.

Example
Accept two numbers from a user and print sum of entered number.
#include<iostream.h>
void main()
{ int n1,n2;
cout<< "Entre Two Number";
cin >> n1 >> n2;
cout << "Sum is : " << n1 + n2;
}

Manipulators
Manipulators are one kind of operators used with the insertion operator <<, to display formatted
output. setw and endl is the most commonly used manipulators in C++. To use these manipulator in
our program, we need to include header file called iomanip.h, because declaration and definition of
it is coded in iomanip.h.
endl manipulator
The endl manipulator is same as escape sequence new line character \n. It is used for new line
indication in an output statement. It will carry remaining message after endl in a new line.

Example
Use of endl
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<< "Welcome"<<endl<<"Hello from AZURE Development Team";
}
Output
Welcome
Hello from AZURE Development Team
setw manipulator
The setw manipulator is used to specify width to print the value of variable or constant. It will
display right-justified output.
Assume that the value of three variables is as follows :
Now Study following program
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int a=345, b=1234, c=89;
cout << a << endl;
cout << b << endl;
cout << c << endl;
}
above program will display output as follows :
345
1234
89
Above output is not ideal for number. It seems that the numbers are hard to understand. It would
be better if they were right aligned as look like as per follows.
345
1234
89

10

It is possible if we specify a specific width for all the number and force them to be printed right
justified. This can be possible using setw manipulator. Following program illustrate use of setw
manipulator to get specific output.
#include<iostream.h>
#include<conio.h>
void main()
{ clrscr();
int a=345, b=1234,
cout << setw(5) <<
cout << setw(5) <<
cout << setw(5) <<
}

c=89;
a << endl;
b << endl;
c << endl;

R setw manipulator is not restricted to numbers; we can use it with Strings also.
Control Structure
Like C, C++ also supports all the three basic control structures and implements them using various
control statements as shown below. This shows the capabilities of C++, it combines the power of
structured programming with the Object-oriented programming.

Control Structure

Selection

if-else

switch

Sequence

do-while

Loop

while

for

The If Statement
C++ allows execution of a statement(s) based on a given condition using if statement. C++ supports
same structure of if statement, which is used in C language. It supports all the form of if statement
used in C Language.

11

Simple form of If Statement


if (expression)
{
Statement(s) block;
}
next statement
Example
Accept String from the user. If entered string is AZURE then print its motto.
#include <iostream.h>
#include <conio.h>
#include <string.h>
void main()
{ clrscr();
char st[20];
cout << "Enter String : ";
cin >> st;
if (strcmp(st,"AZURE")==0)
print("Carving the Career");
}
If Statement with else clause
if (expression)
{ true block;
}
else
{ false block;
}
Example
Accept character from a user and find out whether it is Vowel or Not.
#include <iostream.h>
#include <conio.h>
#include <ctype.h>
void main()
{ clrscr();
12

char ch,x;
cout << "Enter Character : ";
cin >> ch;
x = toupper(ch);
if(x==A || x==E || x==I || x==O || x==U)
cout << ch << " is Vowel";
else
cout << ch << " is Constant, Not a Vowel";
}
R Ternary ( ? : ) operator of C language is valid in C++
Multiple if Statement
if (expression)
{ Statement(s);
}
else if (expression)
{ Statement(s);
}
else if (expression)
{ Statement(s);
}

else
{ statement(s);
}
Example
Accept Student rollno, name and marks of three subjects from the user and print its result with
Grade as per follows.

Avg
>=85
>=75 & < 85
>=65 & < 75
>=50 & < 65
<50

Grade
A
B
C
D
F (FAIL)

13

# include <iostream.h>
void main()
{
int rn,m1,m2,m3,tot;
float avg;
char nm[20],grd;
rn=m1=m2=m3=tot=0;
avg=0.0;
clrscr();
cout << "Enter Name
cin >> nm;
cout << "Enter Roll No.
cin >> rn;
cout << "Enter Mark1
cin >> m1;
cout << "Enter Mark2
cin >> m2;
cout << "Enter Mark3
cin >> m3;

: ";
: ";
: ";
: ";
: ";

tot = m1 + m2 + m3;
avg = (float)tot / 3;
if(avg >= 85)
grd = A;
else if(avg >= 75)
grd = B;
else if(avg >=65)
grd = C;
else if(avg >=50)
grd = D;
else
grd = F;
cout << endl << "Average is : " << avg;
if (grd != F)
cout << endl << nm << " is getting " << grd << "Grade";
else
cout << endl << nm << " is \FAIL\";
}
Nested If Statement
if (expression)
{ 14

if (expression)
statement
else
statement
}
else
{
statement(s);
}
Example
Accept Employee Name, Basic salary and Grade from the user and print its Net Salary using
following calculation.
Grade

Basic Salary

HRA

DA

PF

>=10000
>=5000 and <10000
<5000

15%
14%
13%

12%
11.5%
11%

12.5%
12.5%
12%

>=10000
<10000

13%
12%

12%
11%

12%
10%

>=5000
<5000

12%
11%

11%
10%

10%
-

# include <iostream.h>
# include <stdio.h>
# include <conio.h>
# include <ctype.h>
void main()
{
float bs,hra,da,pf,net;
char nm[20],grd;
clrscr();
cout << "Name
: ";
cin >> nm;
cout << "Grade
: ";
cin >> grd;
cout << "Basic Salary : ";
cin >> bs;
if(toupper(grd) == A)
{ if(bs >= 10000)

15

{ hra = bs
da = bs
pf = bs
}
else
{ if(bs >=
{ hra =
da =
pf =
}
else
{ hra =
da =
pf =
}
}

* 0.15;
* 0.12;
* 0.125;

5000)
bs * 0.14;
bs * 0.115;
bs * 0.125;

bs * 0.13;
bs * 0.11;
bs * 0.12;

}
else
{
if(toupper(grd) == B)
{ if(bs >= 10000)
{ hra = bs * 0.13;
da = bs * 0.12;
pf = bs * 0.12;
}
else
{
hra = bs * 0.12;
da = bs * 0.11;
pf = bs * 0.10;
}
}
else
{ if(toupper(grd) == C)
{ if(bs >= 5000)
{ hra = bs * 0.12;
da = bs * 0.11;
pf = bs * 0.10;
}
else
{ hra = bs * 0.11;
da = bs * 0.10;
pf = 0.0;
}
}
}
}

16

net = bs + hra + da - pf;


cout
cout
cout
cout

<<
<<
<<
<<

"HRA
"DA
"PF
"Net

: " <<
: " <<
: " <<
Salary

hra
da
pf
: "

<<
<<
<<
<<

endl;
endl;
endl;
net << endl;

}
Switch Statement
The switch case statement is a better way of writing a program when a series of if-else occurs.
This is another form of the multiple choice. It is well structured, but can only be used in certain
cases where only one variable is tested and all branches must depend on the value of that variable.
switch (expression)
{
case
value1:
program statement;
......
break;
case
value2:
program statement;
......
break;
case
valuen:
program statement;
.......
break;
default:
.......
break;
}
Example
Accept two numbers and operator from a user and print appropriate result.
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
void main()
{ clrscr();
char op, flag=N;
int n1,n2,tot;

17

cout << "First Number : ";


cin >> n1;
cout << "Second Number : ";
cin >> n2;
cout << "Enter Operator : ";
cin >> op;
switch(op)
{
case + : tot = n1 + n2;
break;
case - : tot = n1 - n2;
break;
case * : tot = n1 * n2;
break;
case / : tot = n1 / n2;
break;
case % : tot = n1 % n2;
break;
default

: flag = Y;

}
if (flag == Y)
cout << "Invalid Choice of operator";
else
cout << n1 << op << n2 << " is " << tot;
}
Loops in C++
C++ allows execution of a statement(s) repetitively using loop construct. C++ supports all the three
loops (for, while and do..while) with same concepts used in C Language. The General form of all
the loops are describe as per follows with its example.
For Loop
For loop is used when number of iteration are known.
for(initialize counter;conditional test;re-evaluation parameter )
{
body of for loop
}

18

Example
Write a necessary code to print following Series.
1, 4, 27, 16, 125, 36, 343, 64, 729, 100
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
void main()
{ clrscr();
for(int I=1;I<=10;I++)
{
if (I % 2 != 0)
cout << setw(4) << I * I * I<<", ";
else
cout << setw(4) << I * I ;
}
}
Example
Write a necessary code to print a to z with its ascii value.
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
void main()
{
char c; int i;
clrscr();
for(c=a; c <=z; c++)
{
i = c;
cout << endl << setw(3) << c << setw(10) << i;
getch();
}
}
While Loop
while loop is used when iteration is based on condition
while(condition)
{
body of while loop ( evaluated when condition is true )
}

19

Example
Accept number(s) from a user till user choice and print sum of entered number.
# include <iostream.h>
# include <conio.h>
void main()
{
char ch = Y;
clrscr();
int n = 0, s = 0;
while(ch == Y || ch == y)
{
cout << "Enter Number : ";
cin >> n;
s += n;
cout << "Want to Continue : ";
cin >> ch;
}
cout << "Sum of Entered Numbers are :" << s;
}
Example
Accept number from a user and find out whether it is Armstrong or not.
# include <iostream.h>
# include <conio.h>
void main()
{
int n = 0, x = 0, i=0, s = 0;
clrscr();
cout << "Enter Number : ";
cin >> n;
x = n;
while ( x > 0)
{ i = x % 10;
x = x / 10;
s+=(i*i*i);
}
if(s == n)
cout << n << " is Armstrong number";
else
cout << n << " is not a Armstrong number";
}

20

do..while Loop
do..while loop is used when iteration is based on condition As you aware, It is very similar to while
loop except the test occurs at the end of the loop body. So, these loop is executed at least once in
case of wrong condition even.
do
{
body of do..while loop
}while(condition);
Example
print the series a to z
# include <iostream.h>
# include <conio.h>
void main()
{ char ch = a;
do
{
cout << ch << ;
ch++;
} while ( ch <= z );
}

Till now, whatever we have seen is same as C language except cout, cin and cascading operator. Next Session onwards we have move on actuality of C++.

21

22

Functions in C++
Like a C Language, In C++ functions provide modularity approach, which is small part of your main
program. A function is a self-contained program segment that carries out a specific, well-defined task.
Functions can be written independent of system-dependent features, making programs more portable.
Also, such programs are more readable and can be well documented. The same function can be called
from many points within a program, avoiding redundant code. A function may or may not take some data
from the main program and may or may not returns value to the caller program. Caller program might be
a main program or another function.
Every C++ program has at least one function, main(). When your program starts, main() is called
automatically. main() might call other functions, some of which might call still others
C++ has added many new features to functions to make them more reliable and flexible. All these
changes have been made to implement object-oriented concepts.
Some New Features in C++ Functions are

Function overloading
Inline function
Friend function
Static function

Prototype of the Function


As we aware that prototype describes the function interface to the compiler by giving details such as the
number and type of arguments and the type of return values. So, one can say prototype is nothing but it is
a declaration of function. Function prototypes are listed at the beginning of the source file. In C language
prototype is a optional, but as you aware (being a good programmer..!) it is considered good practice to
use prototype declarations for all functions that you call in the program. In C++ one cannot ignore prototype
of function like C. It is compulsory in C++. General form of function prototyping in calling program is as
follows:
return_type function_name(argument_list);
The argument_list contains the types and argument names. One can ignore argument_list, If function
does not receive any values from the caller programmer.

23

The return_type indicates the type of value return by the function. If one can ignore return_type then by
default it will consider as integer.
e.g.
int sum(int a, int b);
In a function prototype (function declaration) argument names are dummy variables so they are optional.
Above example of function declaration is written as follows without argument name
int sum(int , int);
Function Definition
The definition contains the actual code for the function. The function body is composed of the statements
that make up the function, delimited by braces. It must have the same number of arguments with the same
types in the same order and have the same return type as describe in its prototype.
The return statement
The return statement terminates the execution of the function and control is passed back to the calling
program (function) with a specified value. There can be any number or return statements or none at all.
If there is no return statement in a function, control passes back to the calling program when the closing
braces of the body part is encountered and it should be declared with void keyword.
The return statement may or may not include a constant, variable or an expression as a returning value.
The expression or variable or constant should be same type of function return_type. The general forma
of return statement is
return(expression);

Calling The Function


The function can be called (invoked) in a program as follows
function_name(argument list if any);
e.g.
count(m,n);

// Function Call

The variable m and n are known as the actual parameters. Note that, the calling statement should not
include type names in the arguments list.
Suppose, if function return any value then it can be called as
x = count(m,n);

// Function Call
24

Here, x will receive the value return by the function.


Example
#include <iostream.h>
#include <iomanip.h>
void line();

// function prototype

main()
{
line();

// function call

cout<< "\n AZURE";


line();
// function call
cout<< endl << "Carving the Career";
line();
// function call
}
void line()
{
for(int k=0;k<60;k++)
cout<<"-";
}

// Function Definition

Output
AZURE
-

Carving the Career


Call by value and Call by reference
The arguments passed in to the function are local to the function. Changes made to the arguments do not
affect the values in the calling function. This is known as call by value or passing by value, which means
a local copy of each argument is made in the function. These local copies are treated just like any other
local variables. It cannot access the actual memory location of the variable and there fore any changes
made to the arguments internally in the function are made only to the local copies of the arguments. Since
only copies of values are being manipulated, the original values in the calling function are never affected
by the called function.
In call by reference the arguments are passed as a pointer to the function. It will allowed to access the
actual memory location of the argument variables and therefore any changes made in called function will
be affected in the calling function. i.e. call by reference method is used to alter the values of original
variables in the calling function,
As an example, consider exchanging two numbers between variables.

25

First lets check what happen if the variables are passed by value:
Example
Following example illustrate Call by Value
#include <iostreamh>
void exchange(int, int);
void main()
{
int a, b;
a = 5;
b = 7;
cout << "Before exchange from main : ";
cout << "a = " << a << " b = " << b << endl;
exchange(a, b);
cout << "After exchange from main : ";
cout << "a = " << a << " b = " << b << endl;
}
void exchange(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
cout << " From exchange function after swapping : ";
cout << "a = " << a << " b = " << b << endl;
}
Output
Before Exchange from main : a=5 b=7
From Exchange function after swapping : a=7 b=5
After Exchange from main : a=5 b=7
In above example, after calling functions actual value of variable does not change. This mechanism is
useful if the function does not need to alter the values of the original variables in the calling program.
Now lets check what happen if the variables are passed by reference:
Example
Following example illustrate Call by Reference
#include <stdio.h>
26

void exchange(int *, int *);


void main()
{ int a, b, *pa , *pb;
pa=&a ; // storing the address of a in pa
pb=&b ; // storing the address of b in pb
a=15;
b=20;
cout << "Before exchange from main : ";
cout << "a = " << a << " b = " << b;
exchange(pa, pb);
cout << "After exchange from main : ";
cout << "a = " << a << " b = " << b;
}
void exchange(int *u, int *v)
{ int temp;
temp = * u;
*u = * v ;
* v = temp;
cout << " From exchange function after swapping : ";
cout << "a = " << a << " b = " << b << endl;
}
Output
Before Exchange from main : a=5 b=7
From Exchange function after swapping : a=7 b=5
After Exchange from main : a=7 b=5

Functions with Default Parameters


For every parameter you declare in a function prototype and definition, the calling function must pass in a
value. The value passed in must be of the declared type. Thus, if you have a function declared as
long myFunction(int);
the function must in fact take an integer variable. If the function definition differs, or if you fail to pass in
an integer, you will get a compiler error in the case of above function.
C++ allows user to call a function without specifying all it argument in case of function prototype declares
a default value for the parameter. A default value is a value to use if none is supplied. The preceding
declaration could be rewritten as

27

long myFunction (int x = 50);


This prototype says, myFunction() returns a long and takes an integer parameter. If an argument is not
supplied, use the default value of 50.
As you know parameter names are not required in function prototypes, this declaration could have been
written as
long myFunction (int = 50);
Declaring a default parameter does not change the function definition. The function prototype for this
function would be
long myFunction (int x)
long myFunction (int)

or

If the calling function did not include a parameter, the compiler would fill x with the default value of 50.
The name of the default parameter in the prototype need not be the same as the name in the function
header; the default value is assigned by position, not name.
Any or all of the functions parameters can be assigned default values. The one restriction is this: If any
of the parameters does not have a default value, no previous parameter may have a default value.
If the function prototype looks like
long myFunction (int Param1, int Param2, int Param3);
you can assign a default value to Param2 only if you have assigned a default value to Param3. You can
assign a default value to Param1 only if you have assigned default values to both Param2 and Param3.

#include <iostream.h>
int AreaCube(int length, int width = 25, int height = 1);
int main()
{
int length = 100;
int width = 50;
int height = 2;
int area;
area = AreaCube(length, width, height);
cout << "First area equals: " << area << "\n";
area = AreaCube(length, width);
cout << "Second time area equals: " << area << "\n";
area = AreaCube(length);
28

cout << "Third time area equals: " << area << "\n";
return 0;
}
AreaCube(int length, int width, int height)
{
return (length * width * height);
}
Output
First area equals: 10000
Second time area equals: 5000
Third time area equals: 2500
Function Overloading
Overloading refers to the use of the same thing for different purpose. Like, depending on situation the
same word expresses a number of different meanings. That is, a single word has multiple meanings its
overloading .
C++ enables you to create more than one function with the same name. This is called function overloading.
The functions must differ in their parameter list, with a different type of parameter, a different number of
parameters, or both. Function overloading implements polymorphism Concepts of OOPs.
Heres an example:
int myFunction (int, int);
int myFunction (long, long);
int myFunction (long);
myFunction() is overloaded with three different parameter lists. The first and second versions differ in
the types of the parameters, and the third differs in the number of parameters. So, one can say an overloaded
function appears to perform different task depending on the kind of data sent to it.
The return types can be the same or different on overloaded functions. You should note that two functions
with the same name and parameter list, but different return types, generate a compiler error. It cannot be
considered as a function overloading.
Example
Following example illustrate use of function overloading with different number of arguments
#include<iostream.h>

29

// Function Prototype
void line();
void line(char);
void line(char, int);
void main()
{
cout<<"\n";
line();
line(*);
line(~,20);
}

// Call First Prototype


// Call Second Prototype
// Call Third Prototype

// Function Definitions
void line()
{
for(int k=0;k<20;k++)
cout<<-;
cout<<"\n";
}
void line(char ch)
{
for(int k=0;k<40;k++)
cout<<ch;
cout<<"\n";
}
void line(char ch, int x)
{
for(int k=0;k<x;k++)
cout<<ch;
cout<<"\n";
}
Output

****************************************
~~~~~~~~~~~~~~~~~~~~
Above program contains three functions with the same name. There are three declarations, three function
calls and different definitions depending of declarations. Here different number of arguments keeps away
to compiler from the confusion and calling statement automatically selects the corresponding function

30

even though the function names are same.


In the above example we have created different functions with the same name with the different number
of arguments but one can have same number of arguments but with the different data type. Thus compiler
can also distinguish between overloaded functions with the same number of arguments, with different
data types.
Example
Following example illustrate function overloading with the same number of arguments but different
types
#include <iostream.h>
int Double(int);
long Double(long);
float Double(float);
double Double(double);
int main()
{
int
long
float
double
int
long
float
double
cout
cout
cout
cout

<<
<<
<<
<<

myInt = 6500;
myLong = 65000;
myFloat = 6.5F;
myDouble = 6.5e20;
doubledInt;
doubledLong;
doubledFloat;
doubledDouble;
"myInt: " << myInt << "\n";
"myLong: " << myLong << "\n";
"myFloat: " << myFloat << "\n";
"myDouble: " << myDouble << "\n";

doubledInt = Double(myInt);
doubledLong = Double(myLong);
doubledFloat = Double(myFloat);
doubledDouble = Double(myDouble);
cout << endl;
cout
cout
cout
cout

<<
<<
<<
<<

"doubledInt: " << doubledInt << "\n";


"doubledLong: " << doubledLong << "\n";
"doubledFloat: " << doubledFloat << "\n";
"doubledDouble: " << doubledDouble << "\n";

31

return(0);
}
int Double(int original)
{
return 2 * original;
}
long Double(long original)
{
return 2 * original;
}
float Double(float original)
{
return 2 * original;
}
double Double(double original)
{
return 2 * original;
}
Output
myInt: 6500
myLong: 65000
myFloat: 6.5
myDouble: 6.5e+20
DoubledInt: 13000
DoubledLong: 130000
DoubledFloat: 13
DoubledDouble: 1.3e+21

In the above example Double() function is overloaded with int, long, float, and double.
The compiler examines the arguments and chooses which of the four Double() functions to call.
Inline Functions
When you define a function, normally the compiler creates just one set of instructions in memory. When
you call the function, execution of the program jumps to those instructions, and when the function return,
execution jumps back to the next line in the calling function. If you call the function 10 times, your program
jumps to the same set of instructions each time. This means there is only one copy of the function, not 10.
There is some performance overhead in jumping in and out of functions. It turns out that some functions
are very small, just a line or two of code, and some efficiency can be gained if the program can avoid
32

making these jumps just to execute one or two instructions. When programmers speak of efficiency, they
usually mean speed: the program runs faster if the function call can be avoided.
If a function is declared with the keyword inline, the compiler does not create a real function: it copies the
code from the inline function directly into the calling function. No jump is made; it is just as if you had
written the statements of the function right into the calling function.
Note that inline functions can bring a heavy cost. If the function is called 10 times, the inline code is copied
into the calling functions each of those 10 times. The tiny improvement in speed you might achieve is more
than swamped by the increase in size of the executable program. Even the speed increase might be
illusory. First, todays optimizing compilers do a terrific job on their own, and there is almost never a big
gain from declaring a function inline. More important, the increased size brings its own performance cost.
Whats the rule of thumb? If you have a small function, one or two statements, it is a candidate for inline.
When in doubt, though, leave it out. Following program demonstrates use of an inline function.
#include <iostream.h>
inline int Double(int);
int main()
{
int target;
cout << "Enter a number : ";
cin >> target;
cout << "\n";
target = Double(target);
cout << "Target: " << target << endl;
target = Double(target);
cout << "Target: " << target << endl;
return 0;
}
int Double(int target)
{
return 2*target;
}
Output
Enter a number : 20
Target: 40
Target: 80

33

In the above program Double() is declared to be an inline function taking an int parameter and returning
an int. The declaration is just like any other prototype except that the keyword inline is preceded just
before the return type.
When above code is executed, this will compiles into code that is the same as if you had written the
following:
target = 2 * target;
everywhere you entered
target = Double(target);
By the time your program executes, the instructions are already in place, compiled into the OBJ file. This
saves a jump in the execution of the code, at the cost of a larger program.
R Inline is a hint to the compiler that you would like the function to be inlined. The compiler
is free to ignore the inline process request and make it as a normal function call.

34

Classes and Objects


As we discuss earlier C++ was initially known as a C with the Classes. So, Classes is the most important
feature of the C++. A Class is a one kind of user-defined data type used in C++. It is an extended version
of C Structure.
As you are aware that C offers programmer to define use-defined data type using structure. It is used
to group logically related data items of different data types. In structure data hiding is not possible so, all
the member variables of structure is accessible within their scope.
R C++ supports all the feature of structures defined in C.
Declaration of Class
A Class is a collection of variables-often of different types-combined with a set of related functions. It
hides data from its external use.
General form of a class declaration is:
class class_name
{
private :
variable declaration;
function declaration;
public :
variable declaration;
function declaration;
};
The Class declaration is similar to a structure declaration. Its declaration starts with keyword class,
followed by the class name. Like a structure, the body of the class is delimited by braces and terminated
by a semicolon.
The class body contains the declaration of variables and functions. These functions and variables are
collectively called members of the class. The variables in the class are referred as the member variables
or data members. The functions in the class typically manipulate the member variables are referred as

35

member functions or methods of the class.


The keywords private and public are known as access specifier. It followed by a colon. The feature of
data hiding is implemented using access specifier. Private members can be accessed only within functions
of the class itself. Public members can be accessed through any object of the class. All members of a
class-variables and functions-are private by default i.e. if you are declared members without access
specifier, by default it will consider as a private member.
The term private means that the data is covered within a class, so that it is not accessed accidentally by
functions or manipulating statements outside the class. That means the data declared under category of
private can only be used or accessed by the member functions of the class. This kind of data is hidden
from the outer world so it will be safe from the accidental manipulation.
Usually the data members within a class is declared as private and the functions are public. However,
there is no rule that data must be private and functions public. One can declare members under any
category of access specifier.
class Number
{
private :
int n;
public :
void getdata()
{ cout << "Enter Number : ";
cin >> n ;
}
void viewdata()
{
cout << endl << "Number is : " << n;
}
};
Above declaration of class consist of one member variable and two member functions. Like C Structure,
declaration of class cannot allocate memory for a Class. It just tells the compiler that which data and
methods are there in the class and what it can do. It also tells the compiler how much space the compiler
must set aside for each Class that you create.
In above example, member variable n is type of an integer, Integer variable occupies two bytes so, Number
Class is two bytes big. getdata() and putdata() takes up no room, because no storage space is set aside
for member functions (methods).
Objects
Declaration of class cannot allocate memory for the class. Once a class has been declared, we can
create variables of it. In C++, the class variable is known as object. So, object is an instance of the class.
Number n1;
36

Above statement will declared n1 object of the Class Number.


When we create an object of the class, the necessary memory space is allocated to that object.

n1
We can declared more than one object of class in a single statement like :
Number

n1,n2;

n1

n2

As shown above each object of class is having separate copies of member variable in it.
Difference between Class and Object
You never pet the definition of a cat; you pet individual cats. You draw a difference between the idea of
a cat, and the particular cat that right now moving all over in your room.
In the same way, C++ differentiates between the class Cat, which is the idea of a cat, and each individual
cat - object. Thus, pussy is an object of type Cat.
Accessing Members
Public member
Public data member can be accessed from outside the class using the objects. It can also access from
another member function of same class. Members of a class can be access by an object of that class
using dot(.) operator.
Calling a public members of the class
Data member
: Object.data_name;
Function member : Object_name.function_name(list of parameters);
For example,
ob.var
ob.func(a,b);

// access of member variable


// access of member function

37

Private member
Private data member of a class can be accessed only through the member functions of that class and not
directly by the object using dot(.) operator.
class temp
{
private:
int num1 ;
void showData(); //prototype of function
public:
int num2;
void getData();

// prototype of function

};
void main()
{
temp t;
t.num1=5;
t.num2=9

// define object of temp class


// error , num1 is private
// OK, num2 is public

t.showData();
t.getData()

// error , showData() is private.


// OK, getData() is public

}
In the above example, num2 and getData() are public member of the class so, we can access them out of
class using object. num1 and showData() are private member of class so, we cannot access them out of
the class.
Example
Create a class called Number, having one member variable to store number. Using one member function
accepts the value of member variable and display entered value using another member function.
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class Number
{
private :
int n;
public :
void getData()
{ cout << "Enter Number : ";
cin >> n ;
}
38

void viewData()
{
cout << endl << "Number is : " << n;
}
};
void main()
{
Number n1;
clrscr();
cout << "First Example of Class" << endl << endl;
n1.getData();
n1.viewData();
}
Example
Create a class called Time, One of the member function will accepts the value of member variable hour,
minute and second from the user and other function will display time in a formatted manner.
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class Time
{
private :
int hh,mm,ss;
public :
void getTime()
{
cout << "Enter Hour
: ";
cin >> hh;
cout << "Enter Minute : ";
cin >> mm;
cout << "Enter Second : ";
cin >> ss;
}
void viewTime()
{ cout << endl;
cout << hh << " : " << mm << " : " << ss << " : " ;
}
};
void main()
{
Time t1;

39

t1.getTime();
t1.viewTime();
}
Array of Object
As a normal variable array one can create an array of the object.
Example
Create a Class called Student. Create a member to perform following tasks.
a) To Accept data of rollno, name and marks of three subjects from the user for 5 Students.
b) To Calculate the Result.
c) To print the result with Grade as per follows :

Avg
>=85
>=75 & < 85
>=65 & < 75
>=50 & < 65
<=50

Grade
A
B
C
D
F (FAIL)

# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class Student
{
int rn,m1,m2,m3,tot;
float avg;
char nm[20],grd;
public :
void getData()
{
clrscr();
cout << "Enter
cin >> nm;
cout << "Enter
cin >> rn;
cout << "Enter
cin >> m1;
cout << "Enter
cin >> m2;
cout << "Enter

Name

: ";

Roll No. : ";


Mark1

: ";

Mark2

: ";

Mark3

: ";

40

cin >> m3;


}
void resultCalculation()
{
tot = m1 + m2 + m3;
avg = (float)tot / 3;
if(avg >= 85)
grd = A;
else if(avg >= 75)
grd = B;
else if(avg >=65)
grd = C;
else if(avg >=50)
grd = D;
else
grd = F;
}
void printResult()
{
cout << endl << "Average is : " << avg;
if (grd != F)
cout << endl << grd << "Grade";
else
cout << endl << "Sorry, \FAIL\";
}
};
void main()
{
Student s1[5];
For(int I=0;I<=4;I++)
{
s1.getData();
s1.resultCalculation();
s1.printResult();
}
}
Scope Resolution operator
In C++, one can declare variable at any place in the program. The scope of variable extends from the
point of its declaration till the end of the block containing the declaration. A variable declared inside a
block is said to be local to that block.
41

int x = 5;

{
int x = 10;

}
}

Block1
Block2

Declaration of x refers to to two different memory locations containing different values. Variable x
declared in block2 cannot refer to the variable x declared in the first block and vice versa.
R Declaration of the same variable in inner block hides a declaration of the same variable in
an outer block.
Global version of variable is not accessible within the inner block, if inner block contains same name local
variable in it. To overcome the problem C++, introduce new operator called the scope resolution operator
( :: ).
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
int I=5;
void main()
{
clrscr();
cout << "main Block" << endl;
int I=10;
cout << I;
{
int I = 20;
cout << "Inner Block" << endl;
cout << I;
cout << " ::I - " << ::I;
}
cout << "main Block, after inner block" << endl;
cout << I;
cout << " ::I - " << ::I;
}
Definition of Member Function Outside of the Class
42

Till now we have seen that we have defined function (body of the function) within the class. Some times
due to more number of functions class becomes longer. To overcome the problem one can defined function
outside of the class using Scope Resolution Operation ( :: ), only declaration is done within the class. This
will increase the readability of the class.
The General form of a member function definition outside of the class
return_type class_name
{
function body
}

:: function_name(arguments)

Example
Create a class called Series to print odd or even number series depends value passed. If number is odd
then print odd number series till that number and same for even number.
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class Series
{
public :
void printSeries(int);
};
void Series :: printSeries(int n)
{
if ((n % 2) == 0)
{
for(int I=1;I<=n;I++)
{
cout << endl;
if(I % 2 == 0)
cout << setw(4) << I;
}
}
else
{
cout << endl;
for(int I=1;I<=n;I++)
{
if(I % 2 != 0)
cout << setw(4) << I;
}
}
}

43

void main()
{
clrscr();
Series s1;
s1.printSeries(12);
cout << endl;
s1.printSeries(9);
}
Output
2
1

4
3

6
5

8
7

10
9

12

Object as Argument
Example
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class Test
{
int a;
public :
int b;
public :
int a_return()
{
return a;
}
void setData(int x, int y)
{ a = x; b = y;
}
void sum(Test t)
{
a = a + t.a_return();
b = b + t.b;
}
void viewData()
{
cout << endl << "Value of a : " << a << endl;
44

cout << "Value of b : " << b << endl;


}
};
void main()
{
int x,y;
clrscr();
Test t1;
t1.setData(10,12);
cout << endl << "t1 Object";
t1.viewData();
Test t2;
cout << endl << "t2 Object";
cout << "Enter value of member variable a : ";
cin >> x;
cout << "Enter value of member variable b : ";
cin >> y;
t2.setData(x,y);
t1.sum(t2);
t1.viewData();
}
Returning Object
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class Double
{
public :
int a,b;
void setData(int x, int y)
{ a = x; b = y;
}
void viewData()
{
cout << endl << "Value of a : " << a << endl;
cout << "Value of b : " << b << endl;
}

45

Double dbl()
{
Double dd;
dd.a = a * 2;
dd.b = b * 2;
return dd;
}
};
void main()
{
Double d1,d2;
d1.setData(10,20);
d2.setData(0,0);
cout << endl << "d1 Object";
d1.viewData();
cout << endl << "d2 Object";
d2.viewData();
d2 = d1.dbl();
d2.viewData();
}

46

Constructor and Destructor


In C++, initialization of the member variable is not possible at the time of the declaration within a Class.
Initialization ensures that variable having such meaningful value in it rather than junk value.
Example
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class test
{
public :
int I,J;
public :
void viewData()
{
cout << endl << "Value of I : " << I << endl;
cout << "Value of J : " << J << endl;
}
};
void main()
{ test t;
t.viewData();
t.I = 10;
t.J = 15;
t.viewData();
}

//Initialization of member variable


//Initialization of member variable

In above example t is an object of test class having two member variables called I and J in it. First call of
viewData() will display junk value of I and J. While second call of viewData() will display 10 and 15 as a
value of I and J because just before of it we have initialized value to member variable.
47

Constructor
To overcome the above problem one has to define variable and then assign a value to it later in the
program using assignment operator as shown in above example.
Other way when you create an object of the class, it can initialize itself, without the need of separate
statement in the program. Automatic Initialization of object is possible using a special member function
called a Constructor.
Constructor is a one kind of special member function of class with no return type, not even void. Its
name is same as the class name. It is called automatically when we create an instance (object) of the
class. It should be declared under category of public access specifier.
When your class is having constructor, it is guaranteed that when you create an object of class it will call
constructor and execute all the statement written as a body of the constructor.
Example
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
class test
{
int I,J;
public :
test()
// Constructor
{
I = 10;
J = 10;
}
void viewData()
{
cout << endl << "Value of I : " << I << endl;
cout << "Value of J : " << J << endl;
}
};
void main()
{ test t;
t.viewData();
}
Constructor is not restricted to initialization process. One can write any valid C++ statement in it.

48

Example
# include <iostream.h>
int I = 0;

//Global Variable

class test
{ public :
test()
//Constructor
{
I++;
cout << "\tHello" << I;
}
};
void main()
{ cout << endl << "First Object"
test t1;
cout << endl << "Second Object"
test t2;
}
Output
First Object
Hello 1
Second Object
Hello 2
In above example I is declared as a global variable. So, it is accessible through out the program.
Now,
test t1;
will create t1 object of the class test. When t1 object is created it will call constructor and increase the
value of I by 1 and display Hello 1 on the screen. While t2 object will display Hello 2 on the screen.
Constructor Overloading
Example
# include <iostream.h>
class Series
{
private :
int start,end,step;
49

public :
Series()
{ start=1; end=10; step=1;
}
Series(int
{ start =
end
=
step =
}

s, int e)
s;
e;
1;

Series(int
{ start =
end
=
step =
}

s, int e, int st)


s;
e;
st;

void printSeries()
{
int I = start;
cout << endl;
do
{ cout << setw(4) << I;
I+= step;
} while(I <= end);
}
};
void main()
{ Series s1;
s1.printSeries();
Series s2(5,15);
s2.printSeries();
Series s3(7,30,3);
s3.printSeries();
}
Constructor With Default Arguments:
It is possible to define constructor with default argument same as normal function. For example the
constructor Test( ) can be declared as follows:
Test( int x, int y=5);

50

The default value of argument y is 5 then the statement:


Test t1(10);
Assigns the value 10 to x and 5 to y (by default). While,
Test t2(10,7);
Assigns the value 10 to x and 7 to y. The actual parameter when specified, overrides the default value.
Copy Constructor
Such time it is required to copies all the value of one object to another object of same class. For that we
require to copy each member of a one object to another object separately. In C++ one object of the any
class may be copied to another object of the same class, either through assignment or argument association.
This is known as Copy Constructor.
The copy constructor is called every time a copy of an object is made. All copy constructors take one
parameter, a reference to an object of the same class.
class Test
{

public :
Test(Test &t)
};

// Copy Constructor

The copy constructor simply copies each member variable from the object passed as a parameter to the
member variables of the new object.
class Test
{
int i;
public :
Test(Test &t)
{ i = t.i;
}
};
As per above discussion, a copy constructor is used to declare and initialize an object from another object.
This can be happened using

51

Test t2(t1);
Test t2 = t1;

or

Above statement will create new object t2 and at the same time initialize value of t1.
Test t2 = t1; statement is also known as copy-initialization.
Remember the statement
t2=t1 ;
will not invoke the copy constructor. But it simply assigns values of all the member variables of t1 object
to t2.
Following example illustrate use of copy constructor.
# include <iostream.h>
class Test
{
int i;
int j;
public :
Test() { }

//Constructor

Test(Test &t)
// Copy Constructor
{
cout << endl << "Use of Copy Constructor";
i = t.i;
j = t.j;
}
void setData(int x, int y)
{
i = x;
j = y;
}
void viewData()
{
cout << endl << "Value of i : " << i << endl;
cout << "Value of j : " << j << endl;
}
};
void main()
{
Test t1;
52

t1.setData(10,20);
cout << endl << "t1 Object";
t1.viewData();
Test t2(t1);
cout << endl << "t2 Object";
t2.viewData();
Test t3 = t1;
cout << endl << "t3 Object";
t3.viewData();
Test t4;
t4 = t1;
cout << endl << "t4 Object";
t4.viewData();
}
Output
t1 Object
Value of i : 10
Value of j : 20
Use of Copy Constructor
t2 Object
Value of i : 10
Value of j : 20
Use of Copy Constructor
t3 Object
Value of i : 10
Value of j : 20
t4 Object
Value of i : 10
Value of j : 20
The new and delete Operator
C++ offers programmers a means to create variables dynamically using the new operator. The new operator
determines the type of the receiving pointer and converts its return value appropriately and allocates
memory depends on type. To release the allocated memory, C++ uses the delete operator.
The new operator, when used with the pointer to a data type, it allocates memory to the object and assigns
the address of that pointer. The new operator can be used to create objects of any type. General form

53

pointer_variable = new data_type


Here pointer_variable is a pointer of type data_type. The new operator allocates sufficient memory to
hold a data object of type data_type and returns the address of the object.
e.g.
int *p = new int;
declare object p. new will allocate necessary to store integer variable in it. (i.e. 2 bytes)
*p = 10
will assign 10 to above created object p.
One can combine above to separate statement in a single statement using :
int *p = new int(10);
One can allocate memory to array and another user-defined data types like structure and class using new
operator.
General form to create single-dimensional array is
pointer_variable = new data_type[size];
Here, size specifies number of elements in the array.
The delete operator does the reverse of new operator. It de-allocates the memory. When data object is
not required in the program we can destroy it using delete operator and release the occupied memory by
the object to reuse it. The General form to delete the object is :
delete pointer_variable;
To release memory of dynamically allocated array following statement is used.
delete [] pointer_variable;
Following program illustrate the use of the new and delete operators:
#include<iostream.h>
int main()
{
char *name;
name = new char[31];
//Allocates 31 bytes
cout << " "Enter Name : ";
cin >> name;
cout << name;
delete []name;
return 0;
}

54

Note the use of the delete operator:


delete []name;
The preceding statement indicates that all the bytes allocated by the new char[] statement are de-allocated.
if you write:
delete name;
then only the first byte is de-allocated, and the rest of the bytes are wasted. Some compilers may even
give an application error.
Destructor
Some times variable is not required after its scope. In such case it is good practice to released unwanted
variables memory. It is possible using Destructor.
Destructor is a one kind of special member function of the class. Its name is same as class name
preceding with tilde (~) sign. A destructor never takes any argument nor returns any value. It is called
automatically when your object moves out of scope. It should be declared under category of public access
specifier. One cannot overload the Destructor.
It will be invoked implicitly by the compiler upon exit from the program or block as the case may be.
Generally it is used to clean up the storage that is no longer required. It is good practice to declare
destructors in a program since it releases memory space for future use.
Example
# include <iostream.h>
# include <string.h>
class Test
{
public :
char msg[20];
Test(char m[])
// Constructor
{
strcpy(msg,m);
cout << endl << "Hello from " << msg << " Constructor ";
}
~Test()
// Destructor
{
cout << endl << "Bye from " << msg << " Destructor";
}
};
void main()

55

{
cout << endl << "***
Test t1("First");
{ cout << endl << "***
Test t2("Second");
}
cout << endl << "***
Test t3("Third");

From main

***";

From Inner Block

Back to main

***";

***";

}
Output
***
From main
***
Hello from First Constructor
***
From Inner Block
***
Hello from Second Constructor
Bye from Second Destructor
***
Back to main
***
Hello from Third Constructor
Bye from Third Destructor
Bye from First Destructor
Static Data Members
A data member of a class can be qualified as static. A static member variable has certain special
characteristics:

It is initialized to zero when the first object of its class created.


Only one copy of that member is created for the entire class and is shared by all the objects of that
class, no matter how many objects are created.
It is visible only within the class, but its lifetime is the entire program.

In sort, static variables are normally used to maintain values common to the entire class. You have
already aware with these in C.
Note that the type and scope of each static member variable must be defined outside the class definition.
This is necessary because the static data members are stored separately rather then as a part of an
object. Since they are associated with the class itself rather than with any class object. They are also
known as class variable.
Example
#include<iostream.h>
class temp
56

{
static int sta;
int normal;
public:
void setData(int i)
{
normal=i;
sta++;
}
void display()
{
cout<<\n Static variable sta =<< sta;
}
};
int temp :: sta;

// sta Defined

void main()
{
temp t1,t2,t3;
t1.display();
t2.display();
t3.display();
t1.setData(4);
t1.display();
t2.setData(8);
t3.setData(9);
t2.display();
t3.display();
}
Output
Static variable sta =
Static variable sta =
Static variable sta =

0
0
0

Static variable sta =


Static variable sta =
Static variable sta =

1
3
3

57

First notice that, following statement in the program used for define static data member.
temp :: sta;

Note that variable sta is initialized to zero when the objects are created.When sta is incremented the data
is read into object. Here three objects (t1,t2,t3) read variable Three times, the variable sta is incremented
three times. Because there is only one copy of sta shared by all the three objects.
Following figure shows how the objects use static variable.

Sharing of a static data member


While defining a static variable, some initial value can also be assigned to the variable. For instance, the
following definition gives sta the initial value 9.
int temp :: sta = 9;
Static Member Functions
We can also have static member functions. A member functions that is declared static has the following
properties.

A static function can have access to only static member ( functions or variables ) declared in the
same class.
A static member function can be called using the class name as follows. Here you need not to
create a object, to call the member function of the class
class-name :: function-name; // instead of its objects

Example
#include<iostream.h>
class temp
{
int sim;

58

static int sta;


public:
void setData()
{
sim=sta++;
}
void showSimple()
{
cout<<\n Simple member = <<sim ;
}
static void showStatic()
{
cout<<\n Static member =<<sta;
}
};
int temp :: sta;
main()
{ temp t1,t2;
cout<<\n Object t1s Data ;
t1.setData();
t1.showSimple();// Accessing Normal function

t1.showStatic();
temp::showStatic();

//Accessing Static function

cout<<\n\n Object t2s Data ;


t2.setData();
t2.showSimple();
temp::showStatic();
}
Output:
Object t1s Data
Simple member = 0
Static member =1
Object t2s Data

59

Simple member = 1
Static member =2
Friend Function
Till now, we are not able to access private member outside the class. But we can access private member
outside the class using friend functions.
Imagine that you want a function to operate on objects of two different classes. Perhaps the function will
take objects of the two classes as arguments and operate on their private data. In this situation theres
nothing like a friend function.
To make an outside function friendly to a class, we have to simply declare this function as a friend of
the class as shown below:class XYZ
{
..
..
public:

friend void fr();

// declaration

};
void fr()
{
// Definition of friend function
}
The function declaration should be preceded by the keyword friend. The function is defined elsewhere in
the program like a normal function.
R A friend function, although not a member function, has full access rights to the private
members of the class.

Some Special characteristics of friend function

It is not in the scope of the class in which it has been declared as friend. (i.e. It is not a member
function of the class)
Since it is not in the scope of the class, it cannot be called using the object of that class. It can
invoke like a normal function without the help of any object.
Unlike member function, it cannot access the member names directly and has to use an object

60

name and dot membership operator with each member name.


It can be declared either in the public or the private part of a class without affecting its meaning.
Usually, it has the objects as arguments.

Following program illustrates the use of a friend function.


Example
#include<iostream.h>
class circle
{
int r;
public:
void setRadius()
{
r=9;
}
friend float Area(circle c);// Friend of circle
};
float Area(circle c)
{
return 3.14*c.r*c.r;
}
main()
{
circle c;
c.setRadius();
cout<<\n Area of circle is :
}

<<Area(c);

Output:
Area of circle is :

254.34

In above example, friend function access the class variable r by using the dot operator and object passed
to it. The function call Area(c) passes the object c by value to the friend function.
Member functions of one class can be friend functions of another class.
In such cases, they are defined using the scope resolution operator as shown in following example. In
following example function getResult(second) is a member of class first and a friend of class second.

61

Example
#include<iostream.h>
class second;
class first
{
int id;
public:
void getId()
{
cout<<\n Enter Id
cin>>id;
}

=;

void getResult(second);
};
class second
{
int marks;
public:
void getMarks()
{
cout<<\n Enter Marks of C++
cin>>marks;
}

=;

friend void first :: getResult(second);


};
void first :: getResult(second s)
{
cout<<\n Students Id
cout<<\n Students C++ Marks
}
main()
{
first f;
second s;

=<<id;
=<<s.marks;

cout<<\n Enter Information of Student ;


cout<<\n ;
62

f.getId();
s.getMarks();
cout<<\n Data of Student ;
cout<<\n ;
f.getResult(s);
}
Output :
Enter Information of Student

Enter Id
=138
Enter Marks of C++
=89
Data of Student
Students Id
Students C++ Marks

=138
=89

In above example, getResult(second) is method of first class and friend of second class. Thats
reason, we can access marks [private data member] of second class using of getResult().
Friend Class
We can also declare all the member functions of one class as the friend functions of another class.
In such case, the class is called a friend class.
Example:
#include<iostream.h>
class beta;

//

Forward declaration

class alpha
{
int data1;
public:
void setAlpha()
{
data1=9;
}
friend class beta;
};

63

class beta
{
int data;
public:
void setBeta()
{
data=6;
}
int sum(alpha a)
{
return data+a.data1;
}
};
main()
{
alpha a;
beta b;
a.setAlpha();
b.setBeta();
cout<<Sum of both class is=
}

<<b.sum(a);

Output:
Sum of both class is=

15

In above example, when ever we declare beta is friend of alpha ( friend class beta ;) thats time compiler
doesnt have any knowledge about beta [ what is beta ] thats reason we can declare beta (class
beta;) before class alpha. This is known as Forward declaration.
Please note that point, class beta is friend of alpha thats reason beta can access private member of
alpha using with object of alpha .but alpha cannot access private member of beta.
A friend function of two class
Example:
#include<iostream.h>
class second;

// Forward declaration

class first
{
int x;

64

public:
void setFirst()
{
x=7;
}
friend int max(first,second);
};
class second
{
int y;
public:
void setSecond()
{
y=5;
}
friend int max(first,second);
};
int max(first f,second s)
{
if(f.x > s.y)
eturn f.x;
lse
eturn s.y;
}
main()
{
first f;
second s;
f.setFirst();
s.setSecond();
cout<<Greater number is =

<< max(f,s);

}
Output:
Greater number is =

In above example, function max(first,second) is friend of first and second class.

65

66

Operator Overloading
A = B + C;
Generally above statement used with basic data types. Suppose A,B and C are an object of any userdefined class than above statement will generate error. But one can make above statement correct using
operator overloading when A,B and C are an object.
Operator overloading is one form of important feature of C++ language called as Polymorphism. As you
aware polymorphism means many form. So, operator can be overloaded to perform different operations
on different data types in different contexts.
In C++, operator overloading creates new definitions for operator and you can change them to do whatever
you want. The mechanism of giving such special meanings to an operator is known as operator

overloading.
Operator overloading occurs with special function of C++, called operator function. The General form of
an operator function is
return_type
operator op(argument_list)
{
function body
}
where, return_type indicates value return by the operator function. op is the any valid operator, which we
want to overload. operator is reserve word.
Operator function must be a member function of class and declared in the category of public access
spicifier. It has a no argument for unary operators and one argument for binary operator.

Unary Operator Overloading


As we aware that ++, and (unary) operator are categorized in the group of unary operator. Unary
operator operates on one operand. So, when it is applied with variable it is restricted to change the value
of only one variable. But when it is used with object it can be change more than one variables value. Now,
lets look how to overload this operator so that it can be applied to an object in much the same as is applied

67

with variable.
Following Example illustrate use of Unary Operator Overloading.
#include <iostream.h>
class Test
{
int i,j;
public :
void setData(int x,int y)
{ i = x;
j = y;
}
void viewData()
{
cout << endl << "Value of i : " << i;
cout << endl << "Value of j : " << j;
}
void operator ++()
{
i = i + 5;
j = j * 2;
}
};
void main()
{
int a,b;
cout << "Value of a : ";
cin >> a;
cout << endl << "Value of b : ";
cin >> b;
Test t1;
t1.setData(a,b);
t1.viewData();
t1++;
t1.viewData();
}

68

Example
Create a Time class, which is used to display time in a proper format. Time class also having member
functions to get and set time. In these class Overload increment operator so that it will increase time by 1
second.
# include <iostream.h>
class Time
{
int hh,mm,ss;
public :
void viewTime();
void setTime(int,int,int);
void getTime()
{ cout << endl;
cout << "Hour
: ";
cin >> hh;
cout << "Minute : ";
cin >> mm;
cout << "Second : ";
cin >> ss;
}
void operator ++()
{
if(ss < 59)
{ ss++;
}
else
{
if(mm < 59)
{ ss = 0;
mm++;
}
else
{
if(hh < 23)
{ ss = mm = 0;
hh++;
}
else
{ ss = mm = hh = 0;
}
}
}
}
};
void Time :: viewTime()

69

{
cout << endl << hh << ":" << mm << ":" << ss;
}
void Time :: setTime(int h,int m,int s)
{ hh = h;
mm = m;
ss = s;
}
void main()
{
Time t1;
t1.getTime();
t1.viewTime();
t1++;
t1.viewTime();
cout << endl;
Time t2;
t2.setTime(18,59,59);
t2.viewTime();
t2++;
t2.viewTime();
}
Returning of Object with Unary Operator Overloading.
Example
#include <iostream.h>
class Test
{
int i,j;
public :
void setData(int x,int y)
{ i = x;
j = y;
}
void viewData()
{
cout << endl << "Value of i : " << i;
cout << endl << "Value of j : " << j;

70

}
Test operator ++()
{
int a = i * 2;
int b = j / 2;
Test temp ;
temp.setData(a,b) ;
return temp;
}
};
void main()
{
int a,b;
cout << "Value of a : ";
cin >> a;
cout << endl << "Value of b : ";
cin >> b;
Test t1,t2;
t1.setData(a,b);
t2.setData(0,0);
cout << endl << "Data before unary operator overloading";
cout << endl << "t1 object";
t1.viewData();
cout << endl << "t2 object";
t2.viewData();
t2 = t1++;

// Operator Overloading

cout << endl << "Data after unary operator overloading";


cout << endl << "t1 object";
t1.viewData();
cout << endl << "t2 object";
t2.viewData();
}
Binary Operator Overloading
Binary operator can be overload as simply as unary operator overloading. Following example illustrate use
of binary operator overloading.
Example
#include <iostream.h>

71

class Test
{
int i,j;
public :
void setData(int x,int y)
{ i = x;
j = y;
}
void viewData()
{
cout << endl << "Value of i : " << i;
cout << endl << "Value of j : " << j;
}
void operator +(int a)
{
i = i + a;
j = j + a;
}
};
void main()
{
int a,b;
cout << endl;
cout << "Value of a : ";
cin >> a;
cout << "Value of b : ";
cin >> b;
Test t1;
t1.setData(a,b);
cout << endl << "Data before binary operator overloading";
t1.viewData();
t1 + 5;

// Operator Overloading

cout << endl << "Data after binary operator overloading";


t1.viewData();
}

72

Return Value with Binary Operator Overloading.


Example
#include <iostream.h>
class Test
{
int i,j;
public
void
{ i
j
}

:
setData(int x,int y)
= x;
= y;

void viewData()
{
cout << endl << "Value of i : " << i;
cout << endl << "Value of j : " << j;
}
int operator +(int a)
{
return(i+j+a);
}
};
void main()
{
Test t1;
t1.setData(10,15);
cout << endl << "Data before binary operator overloading";
t1.viewData();
int x;
x = t1 + 3;

// Operator Overloading

cout << "Value of x is : " << x;


}
Passing Object with Binary Operator Overloading
Example
#include <iostream.h>

73

class Test
{
public :
int i,j;
void setData(int x,int y)
{ i = x;
j = y;
}
void viewData()
{
cout << endl << "Value of i : " << i;
cout << endl << "Value of j : " << j;
}
void operator +(Test t)
{
i += t.i;
j += t.j;
}
};
void main()
{
Test t1,t2;
t1.setData(10,15);
int a,b;
cout << endl;
cout << "Value of a : ";
cin >> a;
cout << "Value of b : ";
cin >> b;
t2.setData(a,b);
cout << endl << "Data before binary operator overloading";
t1.viewData();
t2.viewData() ;
t1 + t2;

// Operator Overloading

cout << endl << "Data after binary operator overloading";


t1.viewData();
t2.viewData();
}
74

Returning Object with Binary Operator Overloading.


Example
#include <iostream.h>
class Test
{
public :
int i,j;
void setData(int x,int y)
{ i = x;
j = y;
}
void viewData()
{
cout << endl << "Value of i : " << i;
cout << endl << "Value of j : " << j;
}
Test operator +(Test t)
{
Test temp;
temp.i = i + t.i;
temp.j = j + t.j;
return temp;
}
};
void main()
{
Test t1,t2,t3;
t1.setData(5,7);
t3.setData(0,0);
int a,b;
cout << endl;
cout << "Value of a : ";
cin >> a;
cout << "Value of b : ";
cin >> b;
t2.setData(a,b);
cout << endl << "Data before binary operator overloading";
cout << endl << "t1 object";

75

t1.viewData();
cout << endl << "t2 object";
t2.viewData();
cout << endl << "t31 object";
t3.viewData();
t3 =

t1 + t2;

// Operator Overloading

cout << endl << "Data after binary operator overloading";


cout << endl << "t1 object";
t1.viewData();
cout << endl << "t2 object";
t2.viewData();
cout << endl << "t31 object";
t3.viewData();
}
Example
Create a Time class, which is used to display time in a proper format. Now add number of Seconds with
the Time object using binary operator overloading and display increased time in a proper format.
# include <iostream.h>
# include <string.h>
# include <conio.h>
class Time
{
public :
int hh,mm,ss;
void viewTime()
{ cout << endl << hh << ":"<< mm << ":"<< ss ;
}
void operator +(int s)
{
int a,b,c;
ss += s;
if(ss >= 60)
{
a = ss / 60;
ss = ss % 60;
mm = mm + a;
if(mm >= 60)
{
b = mm / 60;
mm = mm % 60;

76

hh = hh + b;
if(hh > 23)
{
c = hh % 24;
hh = c;
}
}
}
}
};
void main()
{
Time t1;
t1.hh = 23;
t1.mm = 55;
t1.ss = 39;
t1.viewTime();
t1 + 500;
t1.viewTime();
}

//500 Seconds added to Time object.

77

78

Inheritance
Inheritance is a most powerful feature of OOP. Inheritance is the process by which one object acquires
the properties of another object. It is always nice if we could reuse something that already exist rather
than trying to create the same all over again. It would not only save time and money but also reduce
frustration and increase reliability.
This is important because it supports the concept of hierarchical classification. Consider dog, it is part of
mammal class, which is under the largest class animal. Without the use of hierarchies, each object would
need to define all of its characteristics explicitly. However, by use of inheritance, an object need only
define those qualities that make it unique within its class. It can inherit its general attributes from its
parent.
As per above discussion, In C++ one can create new class from an existing class. In such case new class
is known as a derived class while existing class is know as base class. Derived class inherits partial or all
the properties of its base class and may (Derived class) have another add-ons properties.
Inheritance has important advantages. It permits code reusability. Once a base class is written and
tested, it need not be touched again. As per requirement programmer can be utilized it. Using inheritance
concept, A Programmer can use a class created by another programmer and using inheritance it can add
some more functionality as per requirement.
Creation of Derived Class
One can create derived class with the relationship of their base class as per follows.
class derived_class_name : access_specifier base_class_name
{
};
where, access_specifier may be either private or public. It is optional. If we have not mentioned any
access_specifier, by default it is private.
79

e.g.
class ABC : public XYZ
{ };
class ABC : public XYZ
pronounced as class ABC is publically derived from class XYZ.

According to following figure Base class is having two properties and two methods. This class can work
individually. Derived Class is inheriting property and method of Base Class, so derive class is having
same property as Base Class plus it is also having its own property and method.

Example
#include<iostream.h>
class Emp
{
public :
int empno;
char name[20];
void getData()
{
cout<<"Employee Number:";
cin>>empno;

80

cout<<"Enter Employee Name:";


cin>>name;
}
void putData()
{
cout<< endl << "Employee Number:"<<empno;
cout<< endl << "Employee Name:"<<name;
}
};
class Manager : public Emp
{
private:
int clubcharge;
public:
void getManagerData()
{
getData(); //called the member function of base class
cout<<"Enter Manager Club Charge:";
cin>>clubcharge;
}
void putManagerData()
{
putData(); //called the member function of base class
cout<< endl << "Manager Club Charge:"<<clubcharge;
}
};
void main()
{
Manager m;
m.getManagerData();
m.putManagerData();
}
Here the Emp class is the Base class and Manger class is derived from Emp class. So we can directly used the member
function (getData & putData) in Derived class. Manager class is publically inherited form Emp class.

Protected member
Here we have use new terminology protected for access specifier. Generally this kind of access specifier
is used in case of inheritance.
Protected members of a class can be accessed only through the member functions of that class and not
directly by the object using dot (.) operator. It is carry forward in derived class as a public or protected
depends on Inheritance
81

class temp
{
protected :
int num1 ;
void showData(); //prototype of function
public:
int num2;
void getData();

// prototype of function

};
void main()
{
temp t;
// define object of temp class
t.num1=5; // error , num1 is private
t.num2=9
// OK, num2 is public
t.showData();
t.getData()

// error , showData() is protected.


// OK, getData() is public

}
In the above example, num2 and getData() are public member of the class so, we can access them out of
class using object. num1 and showData() are protected member of class so, we cannot access them out
of the class.
Access Specifier in Derivation
When your derived class is publically inherited from base class,

Private members are not inherited.


public members of base class remains public in derived class.
protected members of base class remains protected in derived class.

When your derived class is privately inherited from base class,

No inheritance made of private members.


public members of base class becomes private in derived class.
protected members of base class becomes private in derived class.

When your derived class is protectedly inherited from base class,

No inheritance made of private members.


public members of base class becomes protected in derived class.
protected members of base class remains protected in derived class.

As you aware, public members of a class can be accessed by its own object using a dot operator.
protected and private member of a class cannot accessible by its own object, but it can be accessible by

82

another members of that class.


Example
# include <iostream.h>
class A
{
int a;
public :
int b;
protected :
int c;
};
class B : public A
{
int d;
};
In above example class B is publically inherited from class A. So, class B consist member variable b as
a public and c as a protected of class A.
Example
# include <iostream.h>
class A
{
int a;
public :
int b;
protected :
int c;
};
class B : private A
{
int d;
};
In above example class B is privately inherited from class A. So, class B consist member variable b and
c of class A as a private in it.
Example
# include <iostream.h>
class A

83

{
int a;
public :
int b;
protected :
int c;
};
class B : protected A
{
int d;
};
In above example class B is protectedly inherited from class A. So, class B consist member variable b
and c of class A as a protected in it.
Overriding Member Functions
You can use member functions in a derived class that have the same name as those in the base class is known
as Overriding. You might want to do this so that calls in your program work the same way for objects of both
base and derived classes. Here is an example of class Employee which is having method called getData() and
putData(). Manager Class is derived from Employee class and having the same name of methods getData()
and putData() as of Base Class.
Example:
class Employee
{
public:
int empno;
char name[10];
void getData()
{
cout<<"Employee Number:";
cin>>empno;
cout<<"Enter Employee Name:";
cin>>name;
}
void putData()
{
cout<< endl << "Employee Number:"<<empno;
cout<< endl << "Employee Name:"<<name;
}
};
84

class Manager : public Employee


{
private:
int sal;
public:
void getData()
{
Employee::getData();//To use method of base class
cout<<"Employee Salary :";
cin>>sal;
}
void putData()
{
Employee::putData();//Valid Statement Public Method
cout<<"Employee Salary :";
cout<<sal;
}
};
void main()
{
Manager M;
Employee E;
M.getData();//It will call method of Manager Class.
E.getData();//It will call method of Employee Class.
}
R The scope resolution operator ( :: ) is used to call the method of base class in derived class.
Multilevel Inheritance
A class can be derived from another derived class as shown in following figure.

The class A is a Base Class for the class B, which is further treated as a Base class for the derived class C. The
85

derived class B is known as Intermediate Base Class since it provides a link for the inheritance between A
and C.
A derived class with multilevel inheritance is declared as follows:
class base
{
. };
class derive1
{
. };
class derive2
{

: access_specifier base_class
: access_specifier base_class
(which is derived class of some another base class)

. };

This process can be extended to any number of levels.


Following Example illustrate the concept of multilevel inheritance.
class Employee
{
public :
int emp_no;
char emp_nm[20];
void getEmployee()
{ cout<<"Employee Number:";
cin>>emp_no;
cout<<"Enter Employee Name:";
cin>>emp_nm;
}

void viewEmployee()
cout<< endl << "Employee Number:"<<emp_no;
cout<< endl << "Employee Name:"<<emp_nm;

}
};
class Account : public Employee
{
protected :
float salary;
public :
void getSalary()
{
cout<<"Employee Salary :";
86

cin>>sal;
}
void viewSalary()
{
cout<<"Employee Salary :";
cout<<sal;
}
};
class Allowance : public Account
{
protected :
float hra;
float da;
public :
void calc_allowance()
{
if(salary > 10000)
{
hra = salary * 0.20;
da = salary * 0.15;
}
else
{
hra = salary * 0.15;
da = salary *.12;
}
}

void view_allowance()
cout<< endl << "HRA :"<<hra;
cout<< endl << "DA :"<<da;

}
};
void main()
{
Allowance a1;
a1.getEmployee();
a1.getSalary();
a1.calc_allowance();
a1.view_allowance();
}

87

Multiple Inheritance
C++ language is the ability to inherit methods and variables from two or more parent classes when building a
new class. This is called multiple inheritance.

The class A and class B is a Base Class for the class C. So, derived class C is having all the characteristic of
Base Class A and B. Multiple Inheritance allows us to combine the features of several existing classes.

The syntax of a derived class with multiple base classes is as follows:


class derive_class : access_specifier base_class1,
access_specifier base_class2 ...
{

};
Example
class A
// Base Class A
{
protected:
int a;
public:
void getA(int x)
{
a=x;
}
};
88

class B
// Base Class B
{
protected:
int b;
public:
void getB(int x)
{
b=x;
}
};

class C : public A, public B // C is Derived from A and B


{
int c;
public:
void getC(int x)
{
c=x;
}
void Disp()
{
cout<<"a="<<a<<"\n";
cout<<"b="<<b<<"\n";
cout<<"c="<<c<<"\n";
}
};
void main()
{
C c1;
c1.getA(5);
c1.getB(10);
c1.getC(20);
c1.Disp();
}
Ambiguity In Multiple Inheritance
The child has two direct base class Parent-1 and Parent-2 which themselves have a common base class
Grandparent via two separate paths. It can inherit directly as shown by the broken line. The grandparent is
sometimes referred to as indirect base class.
Inheritance by the Child as shown in figure might generate some problems. All the public and protected
members of Grandparent are inherited into Child twice via Parent1 and again via Parent2. This means
child would have duplicate sets of the members inherited from Grandparent. This introduces ambiguity and
89

should be avoided using virtual base class.


Virtual Base Class
The duplication of inherited members due to multiple parents can be avoided by making the common base class
(ancestor class) as virtual base class while declaring the direct or intermediate base classes as shown below:
class A
{
.
.
};

//Grandparent

class B1 : virtual public A


{
.
.
};

//Parent1

class B2 : virtual public A


{
.
.
};

//Parent2

class C : public B1, public B2


//child
{
.
//only one copy of A will be inherited.
.
};
When a class is made a virtual base class, C++ takes necessary care to see that only one copy of that class is
inherited, regardless of how many inheritance paths exist between the virtual class and a derived class.
R The keywords virtual and public may be used in either order.
Example
# include <iostream.h>
class Cricketer
{
protected :
char nm[25];
char team[20];

90

void getName()
{ cout<<"Name :";
cin>>nm;
cout<<"Team :";
cin>>team;
}
};
class Bowler : virtual public Cricketer
{
protected :
int wicket;
public :
void getWicket()
{
cout<<"Total wicket :";
cin>>wicket;
}
};
class Batsman : public virtual Cricketer
{
protected :
int runs;
public :
void getRuns()
{
cout<< "Total Runs :" ;
cin >> runs;
}
};
class All_Rounder : public Bowler, public Batsman
{
public :
void getDetails()
{
getName();
getWicket();
getRuns();
}
void viewDetails()
{
cout << endl << "Cricketer
cout << endl << "Team

91

:" << nm;


:" << team;

cout << endl << "Total Runs


:" << runs;
cout << endl << "Total Wickets :" << wicket;
}
};
void main()
{
All_Rounder a1;
a1.getDetails();
a1.viewDetails();
}
Some times in such type of ambiguity, if one want to a call a member function of such specific class though it is
common in more than one class is possible using scope resolution operator.
Object . class_name :: member_function();
Execution order of Constructor in Inheritance
As we aware that constructor is a one kind of special function and it is called automatically when an instance of
class (object) is created. If base class and derived class both are having constructor then base class default
constructor executed first and then the derived class default constructor executed.
Example
# include <iostream.h>
# include <conio.h>
class A
{ public :
A()
{
cout << endl << "Hello from Class A";
}
};
class B : public A
{
public :
B()
{
cout << endl << "Hello from Class B";
}
};
void main()
{ clrscr();
B b1;
}
92

Output
Hello from Class A
Hello from Class B
In case of multiple inheritance, constructor is executed in order of base class used in declaration of derived
class.
Example
# include <iostream.h>
# include <conio.h>
class A
{
public :
A()
{
cout << endl << "Hello from Class A";
}
};
class B
{
public :
B()
{
cout << endl << "Hello from Class B";
}
};
class C : public B, public A
{
public :
C()
{
cout << endl << "Hello from Class C";
}
};
void main()
{ clrscr();
C b1;
}
Output
Hello from Class B
Hello from Class A
Hello from Class C
In case of multiple inheritance if any base class is virtual then execution of constructor starts from virtual base
class. i.e. constructor of virtual base class is executed first.
93

Example
# include <iostream.h>
# include <conio.h>
class A
{
public :
A()
{
cout << endl << "Hello from Class A";
}
};
class B
{
public :
B()
{
cout << endl << "Hello from Class B";
}
};
class C
{
public :
C()
{
cout << endl << "Hello from Class C";
}
};
class D : virtual public B, public C, virtual public A
{
public :
C()
{
cout << endl << "Hello from Class C";
}
};
void main()
{ clrscr();
C b1;
}
Output
Hello from Class B
Hello from Class A
94

Hello from Class C


Hello from Class D
However, if any base class contains a constructor with one or more arguments with default constructor and one
want to execute a constructor with parameter from a derived class then it is mandatory for the derived class to
have a constructor and pass the arguments to the base class constructors.
# include <iostream.h>
# include <conio.h>
class A
{
public :
A()
{
cout << endl << "Hello from Class A";
}
A(int a)
{ cout << endl << "Hello from Class A - para";
}
};
class B : public A
{
public :
B()
{
A(5);
cout << endl << "Hello from Class B";
}
};
void main()
{
B b1;
}

Output
Hello from Class A
Hello from Class A - para
Hello from Class B

95

96

Pointers
Need of Pointers
Suppose you are writing a program that accepts from a user the scores of the students in a class. The program
calculates the average score and displays a sorted list of all the scores. You will need to store the scores of
students in an array. Assuming there are fifty students in a class, you can create an integer array, as given
below:
int scores[50];
You will compile the program containing the above statement and give it (or sell it!) to all the schools. However
there is a problem every school has a different number of students per class. You may think of following
solutions:

Write a different program for each school. There are a hundreds of them!

Locate the school with the highest number of students and define an array containing this number of
elements. For example:
int scores[80];

The program will now allocate 80 * 2 = 160 bytes of memory. But, what if there are only five students per
class? The remaining bytes would be wasted. What if numbers of students are increase from eighty to hundred?
You would rewrite, recompile and redistribute the modified program to every school.
The way to solve this problem is through the allocation of the required memory at the time of execution. This is
known as dynamic allocation of memory. This can only be achieved with the help of a special type of variable,
a pointer variable, also called pointer. A pointer is a variable that stores the memory address of another
variable, rather than its stored value.
Most of the programming languages use pointer variables. However, some languages like Java hide their use
from the programmer.
Use of Pointer
Here are some common uses:

Accessing array elements


Passing arguments to a function when the function needs to modify the original argument

97

Passing arrays and strings to functions


Obtaining memory from the system
In database programs, where the number of records to be stored is unknown at the tome of designing
the database.
Heavily used in any software like an operating system, which interacts directly with the hardware.

Advantages of using the pointer


The various advantages of using the pointers are:

Pointers allow direct access to individual bytes in the memory. Thus, data in the memory is accessed
faster than through ordinary variables. This speeds up the execution of program

Pointers allow direct access to the output devices like the monitor. This speeds up program that are
graphic-intensive.

Pointes allow the program to allocate memory dynamically, only when required, with the help of new
operator. They also allow the program to free the memory when it is no longer required. This is done
with the help of delete operator. You have already seen it in past.

Pointer Variable
The ideas behind pointers are not complicated. Heres the first key concept: every byte in the computers
memory has an address (location number). Addresses are numbers, just as they are for houses on a street.
The numbers start from 0 and go up from there1, 2, 3, and so on. If you have 640k of memory, the highest
address is 6,55,359; for 1 MB of memory, it is 10,48,575.
Consider the following definition and initialization of a character variable:
char

var3 = B;

The above definition will reserve a byte in memory (char variables needs only one byte), name the byte as
var3, and place the character B in that byte. You may represent the variable, var3, int the memory as:
1000

address of the variable

value of the variable

var3

Name of the variable

To obtain the address of a variable, the & (address of) operator must be used before the variable name.
The following program displays the address of a character variable, var3:
#include<iostream.h>
int main()
{
98

char var3=B;
cout << "Name of the variable is : var3 " <<endl;
cout << "Value of the variable is : " << var3<<endl;
cout << "Address of the variable is:"<<&var3;
cout << "Address of the variable is:"<<(unsigned)&var3;
return 0;
}
Output
Name of the variable is :
Value of the variable is :
Address of the variable is
Address of the variable is

var3
B
: 0x8fadfff4
: 65525

R You may have different Output for the address of the variable.

By, default the address of the variable is displayed in the hexadecimal number system. Typecasting of the
address (unsigned)&var3 is required to display the address in the decimal number system.
The operating system decides, at the time of execution of the program, which addresses to allocate to the
variable. It allocates an area in the process address space that has not already been taken by any other variable
or process code. Hence, the address of a variable might change with each execution of the program.
R The & operator is used to define a reference as well as to obtain the address of a variable. In
this lesson, the & operator is used to obtain the address of a variable.
The potential for increasing our programming power requires an additional idea: variables that hold address. We
have seen a variables type that stores characters, integers, floating-point numbers, and so on. Addresses are
stored similarly. A variable that holds an address value is called a pointer variable, or simply a pointer and
declared as
type *variable_name;
type *object_name;
e.g.
char *cptr;
//pointer to char
int *iptr;
//pointer to int
Distance *distptr; //pointer to user-defined distance class
As per above discussion & operator is used to obtain the address of a variable / object.
var2 = &var1;
will place address of var1 into var2. Here var1 and var2 variable or object of same data type.

99

The next program shows the syntax for pointer variables:


#include<iostream.h>
void main()
{
int var1 = 5;
int var2 = 10;
//following statement print address of variables
cout<<endl<<(unsigned)&var1<<endl<<(unsigned)&var2;
int *ptr;
ptr = &var1;
//pointer points to var1
cout << endl << (unsigned)ptr;
//print pointer value
ptr = &var2;
//pointer points to var1
cout << endl<< (unsigned)ptr;
//print pointer value
}
This program defines two integer variables, var1 and var2 and initializes them to the values 5 and 10.
The * means pointer to. The operator * is called the indirection operator. Thus the statement
int *ptr;
defines the variable ptr as a pointer to int. This is another way of saying that this variable can hold the addresses
of integer variables.
ptr = &var1;
Above statement indicates ptr contains the address of var1.
Pointer Arithmetic
The following operations can be performed on a pointer:
Example
Positioning the pointer to an element of an array.
int
b =
b =
c =

a[10], *b, *c;


a;
b + 3; //position b at the element number 3
b 2; //position c at the element number 1

int a,b,c *p1, *p2;


p1 = &a;
100

p1++;
p1;

//points next variable after a (i.e. b)


//points previous variable

the following operations cannot be performed on a pointer; they result in a compilation error:

Addition of two pointers


Multiplication of two pointers
Division of a pointer by a number

Pointers and Arrays


As you have seen previously, an array is a collection of elements of a single data type stored in adjacent
memory locations. The name of an array is resolved by the compiler to yield the base address (address of the
element number [0] of the array). The base address of an array cannot be changed because it is a constant
value.
If an Integer variable occupies two bytes of memory, then each element of an integer array would also occupy
two bytes. Assume that a pointer is assigned the address of the starting element of the array.
Consider the following program:
#include<iostream.h>
int main()
{
int numarr[] = {10, 20, 30, 40};
int *ptr= numarr;
cout << *ptr <<endl;

//displays 10

ptr++;
cout << *ptr <<endl;
cout << *(ptr - 1)<<endl;
cout << *(ptr + 1)<<endl;

//displays 20
//displays 10
//displays 30

ptr;
cout << *ptr <<endl;
cout << sizeof(numarr)<<endl;

cout <<sizeof(ptr)<<endl;
return 0;

//displays 10
//displays 8 the number of bytes
//occupied by numarr

//displays 2

101

Pointers to Objects
Pointers, as seen earlier, can be made to point to objects as well. The usage of pointer with classes is exactly like
that of its usage with structures. As with Structures the Arrow operator (->) can be used to access members
of the class.
Like Student st; declare st as a object of class Student. We can define a pointer object of class Student as
per follows.
Student *pst;
Object pointers are useful in creating objects a t run time.
#include<iostream.h>
class Student
{
private:
int rn;
char nm[20];
public:
void getData()
{
cout << "Enter Rollno
cin >> rn;
cout << "Enter Name
cin >> nm;
}
void viewData()
{
cout << endl << "Rollno
cout << endl << "Name
}
};
void main()
{
Student st;
st.getData();
Student *pst=&st;
pst->viewData();
}
102

:";
:";

:" << rn;


:" << nm;

When we create an object of our class, the member functions of class can access using dot operator, while
arrow operator is used for object to pointer to access the member functions or variables.
In above example pointer pst is initialized with the address of st object.
new operator is also used to create pointer object as follows.
Student *ptr_st = new Student;
Above statement allocates necessary memory space for the data members in the object and assigns the address
of the memory space to ptr_st.
We can create an array of objects using pointers as per follows.
Student *ptr = new Student[10];
Create memory space for an array of 10 object of Student and point to the first object.
Example :
#include <iostream.h>
class box
{
int length;
int width;
public:
box(void);
//Constructor
void set(int new_length, int new_width);
int get_area(void);
};

box::box(void)
{
length = 8;
width = 8;
}

//Constructor implementation

void box::set(int new_length, int new_width)


{
length = new_length;
width = new_width;
}

103

int box::get_area(void)
{
return (length * width);
}
int main()
{
box small, medium, large;
box *point;
small.set(5, 7);
large.set(15, 20);
point =
cout <<
cout <<
cout <<

new
"\n
"\n
"\n

//A pointer to a box

box;
The small box area is : " << small.get_area();
The medium box area is : " << medium.get_area();
The large box area is : " << large.get_area();

cout << "The new box area is " << point->get_area() << "\n";
point->set(12, 12);
cout << "The new box area is " << point->get_area() << "\n";
delete point;
return 0;
}
Output :
The
The
The
The
The

small box area is 35


medium box area is 64
large box area is 300
new box area is 64
new box area is 144

A Constructor, if defined is invoked when an object pointer is allocated memory through new operator. Similarly,
a destructor is invoked when memory allocated to an object pointer is released through delete operator.
Pointers to Derived Class
In C++, pointers cannot restrict to the base objects but it can points to the object of derived class. Pointers to
object of a base class are type-compatible with pointers to objects of a derived class. Therefore a pointer
variable can be point to objects of different classes.
If B is a base class and D is derived class from B, then a pointer declared as a pointer to B can also be a pointer
to D.
B *ptr;
104

B b1;
D d1;
ptr = &d1;
However, pointer can sometimes problematic with inheritance. When base class pointer points to derived class
object, it can access only those members of base class, which is inherited. It cannot access any member of
derived class. The following example illustrates problem occurs with inheritance.
#include <iostream.h>
#include <conio.h>
class B
{
public:
int b;
void show()
{ cout << endl << "Base Class";
cout << endl << "b : " << b;
}
};
class D : public B
{
public :
int d;
void show()
{ cout << endl << "Derived Class";
cout << endl << "b : " << b;
cout << endl << "d : " << d;
}
};
void main()
{ clrscr();
B b1;
B *bptr = &b1;
bptr->b = 5;
bptr->show();
b1.show();
D d1;
bptr = &d1;
bptr->b = 10;
// bptr->d = 20;

Not Work

105

bptr->show();
}
Output
Base Class
b : 5
Base Class
b : 5
Base Class
b : 10
In Inheritance, when pointer of base class points to derived class object and member of derived class having the
same name as the members of base class, then any reference to that member by pointer will always access the
base class member.
#include <iostream.h>
#include <conio.h>
class B
{
public:
void show()
{ cout << endl << "Hello from Base Class";
}
};
class D1 : public B
{
public :
void show()
{ cout << endl << "Hello from Derived Class1";
}
};
class D2 : public B
{
public :
void show()
{ cout << endl << "Hello from Derived Class2";
}
};
void main()
{
106

clrscr();
B *bptr;
B b1;
D1 d1;
D2 d2;
bptr=&b1;
bptr->show();
bptr=&d1;
bptr->show();
bptr=&d2;
bptr->show();
}
Output:
Hello from Base Class
Hello from Base Class
Hello from Base Class
Above example contains a base class called B. Two other classes D1 and D2 are derived from this base
class.
In the function main() we have declared a pointer to the base class and two object of derived class D1 and D2
respectively. Pointer to base class is assigned with the address of both the derived class object.
When we assign the address of the derive class to the pointer of the base class, the function from the base class
is executed. Because objects of derived classes are type-compatible with pointers of base class. So, compiler
ignores the contents of the pointer and chooses the function from the same class as that of the pointer.
This problem is solved using virtual function.
Virtual Functions
Virtual means existing in effect but not in realty. A virtual function is one that does not really exist but nevertheless
appears real to some parts of a program. Late binding is implemented by the use of the virtual keyword within
the class hierarchy. A function is declared as virtual in the base class, and in each subclass, a function with the
same name is coded. When such functions are invoked using a base class reference or a pointer, the actual
function invoked depends on the type of the object, which is referenced.
Syntax
virtual

<data_type> <function_name>();

107

Example
#include <iostream.h>
#include <conio.h>
class B
{
public:
virtual void show()
{ cout << endl << "Hello from Base Class";
}
};
class D1 : public B
{
public :
void show()
{ cout << endl << "Hello from Derived Class1";
}
};
class D2 : public B
{
public :
void show()
{ cout << endl << "Hello from Derived Class2";
}
};
void main()
{
clrscr();
B *bptr;
B b1;
D1 d1;
D2 d2;
bptr=&b1;
bptr->show();
bptr=&d1;
bptr->show();
bptr=&d2;
bptr->show();
}
108

Output:
Hello from Base Class
Hello from Derived Class1
Hello from Derived Class2
Example
#include<iostream.h>
class Person
{
protected:
char name[20];
char city[15];
public:
virtual void accept()
{
cout <<"Enter Name
cin >> name;
cout <<"Enter City
cin >> city;
}
virtual void display()
{
cout << "Name :
cout << "city :
}
};

: ";

: ";

" <<name<<endl;
" <<city<<endl;

class Customer : public Person


{
private:
int age;
public:
virtual void accept()
{
Person::accept();
cout << "Enter Age
: ";
cin >> age;
}
virtual void display()
{
Person::display();
Cout << " Age
:
"<<age<<endl;

109

}
};
class Dealer : public Person
{
private:
int price;
public:
virtual void accept()
{
Person::accept();
cout << "Enter Price
cin >> price;
}
virtual void display()
{
Person::display();
Cout << " Price
:
}
};

";

"<<price<<endl;

int main()
{
Person *ptr;
ptr = new Customer;
ptr->accept();
ptr->display();
ptr = new Dealer;
ptr->accept();
ptr->display();
return 0;
}
Pure Virtual Functions
A pure virtual function is a virtual function with no body (another OOP sentence that sounds as if it described
an esoteric religious concept). There is no need for the base-class version of the particular function; we only use
the versions of the function in the derived classes. When this is true, the body of the virtual function in the base
class can be removed, and the notation =0 added to the function declaration, as shown in the example:
#include <iostream.h>
#include <conio.h>
class B
{
public:
virtual void show() = 0;
};
110

class D1 : public B
{
public :
void show()
{ cout << endl << "Hello from Derived Class1";
}
};
class D2 : public B
{
public :
void show()
{ cout << endl << "Hello from Derived Class2";
}
};
void main()
{
clrscr();
B *bptr;
B b1;
D1 d1;
D2 d2;
bptr=&b1;
bptr->show();
bptr=&d1;
bptr->show();
bptr=&d2;
bptr->show();
}
Example
#include <iostream.h>
class Base
{
public:
virtual void show( ) = 0;
};

111

//base class

//pure virtual function

class Derv1 : public Base


{
public :
void show( )
{ cout << "\nDerv1"; }
};
class Derv2 : public Base
{
public :
void show( )
{ cout << "\nDerv2"; }
};
void main( )
{
Base* list[2];
Derv1 dv1;
Derv2 dv2;

//derived class 1

//derived class 2

//List of pointers to base class


//object of derived class 1
//object of derived class 2

list[0] = &dv1; //put address of dv1 in List


list[1] = &dv2; //put address of dv2 in List
list[0] -> show( ); //execute show( ) in both objects
list[1] -> show( );
}
Now the virtual function is declared as
virtual void show() = 0;

//pure virtual function

The equals sign here has nothing to do with assignment; the value 0 is not assigned to anything. The =0 syntax
is simply how we tell the compiler that a function will be pure that is, have no body.
You might wonder, if we can remove the body of the virtual show( ) function in the base class, why we cant
remove the function altogether. That would be even cleaner, but it doesnt work. Without a function show( ) in
the base class, statements like
bptr -> show( );
Would not be valid, because the pointers bptr must point to members of class Base.
Abstract Classes
An abstract class often defined as one that will not be used to create any objects, but exists only to act as a base
class of other classes. Ellis and Stroustrup tighten up this definition by requiring that, to be called abstract, a class
must contain at least one pure virtual function.
112

File Handling in C++


In C++, Input and Output system is designed in such way to work with all kind of devices including
terminals, disks and tape drives. C++ I/O system provides a common interface to handle I/O operations.
This interface is independent from actual device although each device is different. This interface is
known as stream.
A stream is a sequence of bytes; act either as a source from which the input data can be obtained or as a
destination to which the output data can be sent. So, A Stream is a source or destination for a collection
or a flow of data.
There are two kinds of streams:
Output streams : Allow you to write or store characters
Input streams : Allow you to read or fetch characters
The input and output capabilities of C++ streams are derived from the fact that each stream is associated
with a particular class. For example, the input streams are associated with the istream class and the
output streams are associated with the ostream class. Each class contains its own data members, functions,
and definitions for dealing with the data in a particular stream.
The figure below shows the hierarchy of the stream class library.

ios

istream

ostream

iostream
Stream Class Hierarchy
The ios class is a base class of the stream class hierarchy. It defines the basic format for input/put and
error control procedures. The istream and ostream are derived from it.
113

The istream (input stream) class is used to define the format in which data is received from the keyboard
(standard input device).
The ostream (output stream) class is used to define the format in which data is displayed on the VDU
(standard output device).
The iostream (inout and output stream) class is derived from the istream and ostream classes through
multiple inheritance. Therefore, it inherits both the input and output attributes.
File Class Hierarchy
C++ provides File stream classes that are used to access disk files. The figure given below shows the
stream class hierarchy that provides file input and out capabilities.

ios

istream

ostream

iostream

ifstream

fstream

ofstream

The three class deals with file input and output are:
fstream : Is derived from iostream and is used for both file input and output
ifstream : Is derived from istream and is used for file input (reading)
ofstream : Is derived from ostream and is used for file output (writing)
The I/O System of C++ handles file operations, which are very much similar to the console input and
output operations. It uses file streams as an interface between the programs and the files. Input stream
extracts (or reads) data from the file and the output stream inserts (or writes) data to the file.
All above classes, designed to manage the disk files, are declared in fstream.h and therefore we must
include this file in any program that uses files.
Types of Files
The files in C++ can be differentiate based on its storage. One can store file in text form or one can store
file in binary form. In a text-based file, the information is stored in the same format as it is displayed on
114

the screen. The files using binary input and output save data in actual representation of the data type.
Opening and Closing a file
If we want to use a disk file, we need to decide the following things about the file and its intended use :
Suitable name for the file
Data type and structure
Purpose
Opening method
The file name is a string of characters that make up a valid filename for the operating system. It contains
two parts, a primary name with optional secondary name.
As stated earlier, for opening a file, we must first creat a file stream and then link it to the filename. A file
stream can be defined using the classes ifstream, ofstream and fstream that are contained in the header
file fstream.h. The class to be used depends upon purpose, whether we want to read data from the file
or write data to it.
A file can be opened in two ways :
Using the constructor function of the class.
Using member function open() of the class.
Opening files using constructor
As we aware constructor is used to initialize an object while it is being created. Here, a filename is used
to initialize the file stream object.
To, create an output file using class ofstream
ofstream ofile(student);

//output only

(Writing Purpose)

Above statement will creates ofile object of ofstream that manges the output stream. This statement also
opens the file student and attaches it to the output stream ofile.
Similarly, the following statement declares ifile as an ifstream object and attaches it to the file data for
reading.
ifstream ifile(student);

//input only (Reading Purpose)

Let us first start of creation of file.


Example
# include <fstream.h>

115

void main()
{
ofstream ofile(ABH.TXT);

// Creates a file for output

ofile << File Handling Example;


ofile << endl << AZURE;
ofile << endl << Carving the Carrer;
}
When we execute above program ABH.TXT file is created and line of text are written in to the file. There
will be no output on the screen. To see the content file, open the file ABH.TXT using notepad or edit.
The connection with a file is terminated (closed) automatically when the object moves out of scope. If
one want to explicitly close the file then close() method of file object is used.
file_object.close();
Example
# include <fstream.h>
void main()
{
int n;
char st[20];
cout << endl << Enter Number : ;
cin >> n;
cout << endl << Enter String : ;
cin >> st;
ofstream ofile(Test.TXT);
ofile << n;
// Writes value of n in to the test.txt
ofile << st; // Writes value of st in to the test.txt
ofile.close();
ifstream ifile(Test.TXT);
ifile >> n;
ifile >> st;
cout << n : << n;
cout << st : << st;
}
R When you create a file with ofstream object, new file is created if there is no file of that
name. If a file by that name is already exists then its overwrite the contents of existing file.

116

Open file with open() function


you can open a file for writing as well as reading by using the open() function.
Example
ofstream ofile;
ofile.open(data.dat);

//Associates the stream to a File

Here, an object named ofile of the ofstream class is created. The constructor of the ofstream class is
invoked with the value, data.dat. When the scope of the ofstream in a program is over, the destructor of
the ofstream class is automatically called, and the file is closed.
ofstream ofil;
ofil.open(data.dat,ios::app); //Associates the stream to a File
Here, first parameter for the open() function is the name of the disk file and the second parameter implies
the way a file should be opened. ios::app indicates that the file should be opened in the append mode.
Getting the Right Path

If your input file is not stored in current working directory, you may need to use an operating system path
to locate it. For the DOS and Windows operating systems, which use \ to separate directory names, the
escape sequence \\ (two backslashes) must be used to specify full path names. So the file name may
appear like this:
ifstream inFile(C:\\myFolder\\mySubFolder\\myFile.dat);
where \\ represents only one backslash. Omitting one \ from \\ is virtually guaranteed to result in not
finding the file.
This problem dosent exists in Unix, Linux as the / character is used to separate directories, and so / can
be used as is.
Open Mode Bits
Each stream has a series of bits or flags associated with the operations. These bits are defined in the ios
class. The bits that are associated with the opening of files are called open mode bits. These bits represent
the mode in which the file is opened. If the file is opened in the output mode, a particular mode is set on.
Likewise, if the file is opened in the input mode, another bit is set on. Collectively, these bits state the
method in which the file is to be opened. The following statement opens a file in the input and output
modes:
fstream

fil(data.dat,ios::in | ios::out);

117

in and out bits means that the object, fil, has to be opened for both writing and reading. The pipe ( | ) is the
bitwise OR operator. When the program encounters this statement, these two bits are set ON in the bit
stream and, therefore, allow the file to be opened in either input or output mode.
The following table shows the file opening modes:
Mode
app
in
out
ate
trunc

Explanation
Starts reading or writing at the end
Opens for reading
Opens for writing
Seeks the end-of-file
Truncates a file if it exists

Reading and Writing File Character by Character


The put() and get() functions, which are member functions of ostream and istream respectively are used
to output and input a single character at a time.
<output_object>.put(<character_variable>);
<input_object>.get(<character_variable>);
Example
# include <fstream.h>
# include <string.h>
void main()
{
char st[]=AZURE Research Team;
ofstream ofile(test.txt);
for(int I=0; I<=strlen(st); I++)
ofile.put(st[I]);
ofile.close();
char c;
ifstream ifile(test.txt);
while(ifile)
{
ifile.get(c);
cout << c;
}
}
One can perform above operation with fstream object using different open mode.
118

# include <fstream.h>
# include <string.h>
void main()
{
char st[]=AZURE Research Team;
fstream fl(test.txt, ios::out);
for(int I=0; I<=strlen(st); I++)
ofile.put(st[I]);
fl.close();
char c;
fstream fl(test.txt,ios::in);
while(fl)
{
fl.get(c);
cout << c;
}
}
Detecting end-of-file
eof() is a member function of ios class. It returns non-zero value if the end-of-file(EOF) is encountered,
and a zero otherwise. Therefore following statement terminates the program on reaching the end of the
file.
if(fl.eof() != 0)
{
exit(1);
}
In previous program we have used statement like :
while(fl)
An object of ifstream returns a value 0, if any erro occurs in the file operation including the end-of-file
condition. Thus, while loop terminates when fl object returns a value of zero on reaching the end-of-file
condition.
The write() Function
The write() function writes data, one object at a time, in a binary format. So, here data are store in the file
in the same format in which they are stored in the internal memory. The binary format is more accurate
for storing the numbers as they are stored in the exact internal representation.
write((char *) address, int size);

119

It expects two parameters:


The address of the object that contains the data to be written to the file
The size of the object that is to be written to the file
The following program accepts one set of data and writes it to a file using the write() function.
#include <fstream>
class bill
{
char cust_nm[30];
float bill_amt;
public :
void getData()
{ cout << endl << Customer Name : << cust_nm;
cout << endl << Bill Amount : << bill_amt;
}
};
void main()
{
ofstream ofil(data.dat);
Bill bobj;
bobj.getData(); //Member Function of Bill Class
ofil.write((char *)&bobj,sizeof(bobj));
}
In the above program, &bobj is the address of the variable containing the data to be written to the file. In
the code, (char *) is a type cast. This type casting is required because the first parameter to the write()
function is a character pointer. Therefore, the compiler assumes that the variable is of the character type,
and the address of the object has to be type cast to a character pointer. The sizeof() operator computes
the size of any variable or type and helps to eliminate machine-dependent code from programs.
File Pointers
C++ input and output system manages two integer values associated with a file. Both these values are
very useful when data is to extracted or written to the file. File pointers gives use exact location in the file
for writing data into a file and reading data from a file.
The seekp() Function
The C++ output system manages an integer value associated with a file. The integer value associated with
a file for output operations is:

120

put pointer specifies the location in the file where the next write operations will occur. i.e., from which
point in the file next record will be written.
The seekp() function moves the put pointer to an absolute address within the file or to a certain number of
bytes from a particular position.
The seekp() function takes two arguments:

The number of bytes after which the pointer is to be positioned.


The reference in the file to which the put pointer has to be positioned

Example
ofstream ofil;
ofil.seekp(10,ios::beg);
the above code positions the put pointer 10 bytes from the beginning of the file.
There are three reference points defined in the ios class:
ios::beg Beginning of the file
ios::cur Current position of the file pointer
ios::end End of the file
The tellp() Function
The tellp() function returns the current position of the put pointer. It returns exactly at what position put
pointer is located whether it at the end of file or at the beginning or some where in the between. It is useful
as you come to know from where next write action will be performed.
Example
int position;
ofstream ofil;

ofil.seekp(0,ios::end);
position = ofil.tellp();
if(position == 0)
{
cout << Writing the first record.;
}

The above example displays the message Writing the first record. if the file is empty.
The read() Function
The read() function is used to read the data from a file that has been writing using the write() function.
121

This function is called with two arguments. These are: The address of the variable into which the data has
to be read and the size of the variable
Syntax
read((char *) addr, int size);
The following program illustrates the use of the read() function to read one record from a file.
#include<fstream>
int main()
{
bill billobj;
ifstream ifile(billfile.dat);
ifile.read((char *)&billobj,sizeof(billobj));
billobj.showdata(); //displays the data on the screen
return 0;
}
There are other ways of reading from a file. The get() member function to the ifstream class reads a
string, one character at a time, from a file.
The ifstream class also provides the >> operator to read from a file.
The seekg() Function
Similar to the C++ output system, the input system also manages an integer value associated with a file.
That is the get pointer, which specifies the location in the file, where the next read operations is to occur.
The seekg() functions moves the get pointer to an absolute address within the file or to a certain number
of bytes from a particular position.
The seekg() member function takes two arguments:

The number of bytes after which the pointer is to be positioned.


The reference in the file to which the get pointer has to be positioned.
ifstream ifil;
ifil.seekg(0,ios::end);

the above code positions the get pointer at the end of the file.
The tellg() Function
The tellg() function returns the current position of the get pointer. It is used to verify that from which
location data will be extracted from the file and which number of record will be fetched from the file when
next read task is performed. It is also used to determine size of the file.

122

Example
This program finds the number or records in the file data.txt
#include <fstream.h>
class student
{
private:
int id;
char name[20];
char course[10];
char centre[20];
char city[15];
public:
void getdata()
{
cout << endl <<
cin >> id;
cout << endl <<
cin >> name;
cout << endl <<
cin >> course;
cout << endl <<
cin >> centre;
cout << endl <<
cin >> city;
}

Enter your ID
Enter your Name

:;
:;

Enter your Course Name

:;

Enter name of your centre

:;

Enter in which city it is located

void showdata()
{
cout << ID
<< id<<endl;
cout << Name << name << endl;
cout << Course name << course << endl;
cout << Centre name << centre << endl;
cout << City << city << endl;
}
};
int main()
{
student sobj;
fstream file;
char reply = Y;
file.open(data.dat,ios::out|ios::app);
while(reply == Y || reply == y)

123

:;

{
cout << Enter Students Detail<<endl;
sobj.getdata();
file.write((char *)&sobj,sizeof(sobj));
cout << Do you want to enter another record[Y/N]
cin >> reply;

:;

}
file.close();
file.open(data.dat,ios::in);
file.seekg(0,ios::end);
int end,totrec;
end = file.tellg();
cout << The size of the file is : << end << endl;
cout << Size of one record is : << sizeof(sobj) <<endl;
totrec = end / sizeof(sobj);
cout << There are total << totrec;
cout << records in the file <<endl;
return 0;
}
the above code determines the size of the file.
Example:
#include <iostream>
#include <fstream>
class Customer
{
private:
char name[20];
char city[15];
public:
void print()
{
cout<<Your Name : ;
cout <<name<<endl;
cout<< Your City : ;
cout << city<<endl;
}
void get()
{
cout<<Enter your Name :
cin>>name;
124

cout<< Enter your City


cin>>city;

}
};
int main()
{
Customer cobj;
fstream file;
char reply = Y;
file.open(customer.dat,ios::out|ios::app);
while(reply == Y || reply == y)
{
cout << Enter Customer Details<<endl;
cobj.get();
file.write((char *)&cobj,sizeof(cobj));
cout << Do you want to enter another record[Y/N] :;
cin >> reply;
}
file.close();
file.open(customer.dat,ios::in);
file.read((char *)&cobj,sizeof(cobj));
while(file)
//Read till the end of the File
{
cobj.print();
file.read((char *)&cobj,sizeof(cobj));
}
file.close();
return 0;
}

Example
This example displays Menu to Add, Modify and View data, on selection of users choice task is performed.
#include <fstream.h>
#include <ctype.h>
class Customer
{
private:
int id;
char name[20];
char city[15];
public:
void getdata()

125

{
cout<<Enter your ID : ;
cin>>id;
cout<<Enter your Name : ;
cin>>name;
cout<< Enter your City : ;
cin>>city;
}
void printdata()
{
cout << ID : << id << endl;
cout << Your Name : << name << endl;
cout<< Your City : << city<< endl;
}
void addrec()
{
Customer cobj;
fstream file;
char reply = Y;
file.open(cust.dat,ios::out|ios::app);
while(reply == Y || reply == y)
{
cout << Enter Students Detail<<endl;
cobj.getdata();
file.write((char *)&cobj,sizeof(cobj));
cout << Enter another record[Y/N] :;
cin >> reply;
}
file.close();
}
void modifyrec()
{
int num, var;
Customer cobj;
fstream file
file.open(cust.dat,ios::in|ios::out)
cout << Enter ID to modify : ;
cin >> num;
file.read((char*)&cobj, sizeof(cobj));
while(cobj.is_open()!=0)
// is_open() checks file is open
{
if(cobj.id == num)
{
cobj.printdata();
126

cout << Enter new Data ;


cobj.getdata();
file.seekp(-sizeof(cobj),ios::cur);
file.write((char*)&cobj,sizeof(cobj));
}
file.read((char*)&cobj, sizeof(cobj));
}
}
void viewrec()
{
Customer cobj;
fstream file;
file.read((char*)&cobj,sizeof(cobj));
while(file)
{
cobj.printdata();
file.read((char*)&cobj,sizeof(cobj));
cout << endl << press Enter to continue ;
getch();
}
}
};
int main()
{
Customer cobj1;
int ch;
char ok;
do
{
ok = ;
cout << 1. Add Record <<endl<<endl;
cout << 2. Modify Record <<endl<<endl;
cout << 3. View Records <<endl<<endl;
cout << 4. Exit <<endl<<endl;
cout << Enter your choice : ;
cin >> ch
switch(ch)
{
case 1:
{
cobj1.addrec();
break;
}

127

case 2:
{
cobj1.modifyrec();
break;
}
case 3:
{
cobj1.viewrec();
break;
}
case 4:
{
exit(0);
break;
}
default :
{
cout << Invalid choice <<endl;
ok = n;
}
}
}while(toupper(ok) == N);
return 0;
}

128

Review Questions
1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
12)
13)
14)
15)

16)
17)
18)
19)
20)

21)

What are the differences between the function prototype and the function definition?
Do the names of parameters have to agree in the prototype, definition, and call to the function?
If a function doesnt return a value, how do you declare the function?
If you dont declare a return value, what type of return value is assumed?
What is polymorphism?
What is function overloading?
What is the use of inline function?
What operators can/cannot be overloaded?
Can I create a operator ** for to-the-powerof operations?
Is it OK to convert a pointer from a derived class to its base class?
Why cant my derived class access private : things from my base class?
Explain the terms Static binding and Dynamic binding of member functions with examples.
False is default value of Boolean variable . It is True/False.
Can I make friend variable in c++ program. It is True/False.
Refer following code. X variable is pubic . it is True/Flase.
class simple
{
int x;
};
Runtime Polymorphism is possible in c++.
Exception Handling is possible in c++.It is True/False.
Can I make function in C++ macro. It is True/False.
Following c++ keyword is True/False.
Float
Give the range of int variable.
0 to 256
0 to 255
128 to 127
128 to 128
Following code is True/False.
int *x;
char s=&x;

129

22)

Following two code ( 1 and 2 ) are same or not.


sizeof(x)
sizeof(int)

23)

Following expression is True/False.


9+float(x)

24)

What does the following program segment display


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

25)

Following program segment is True/False.


{

int x=9;
{
cout<<x;
}
}

26)
{

Following program segment is True/False.


int x=9;
{
char x=s;
cout<<x;
}

}
27)

Find errors if any or give output for the following program segment.
int i=9;
do
{
i++; cout<<i;
}while(i>0)

28)

Find errors if any or give output for the following program segment.
int I=9;
switch(I)
{
case 9:
cout<<First;
I++;
break;
130

case 10:
cout<<second;
I++;
case 11:
cout<<third;
I++;break;
case 12:
cout<<forth;
I=I+5;break;
default:
cout<<last;
break;
}
29) What is the problem with the following class definition? What should be the correct definition?
#include<iostream.h>
class circle
{ public:
circle(int x, int y, int r)
{
X=x;
Y=y;
R=r;
}
int radius()
{
return R;
}
int X()
{
return X;
}
int Y()
{
return Y;
}
int X,Y,R;
private:
float area()
{

131

return ( 3.14 * R * R );
}
float diameter()
{
return ( 2 * 3.14 * R );
}
}
30) What are the advantages of function prototypes in C++?
31) Describe the different styles of writing prototypes.
32) What do you meant by overloading of a function? When do we use this concept?
33) What is the difference between public , protected,private members of a class ?
34) What can be the possible reason for declaring a member function as private?
35) What is the basic difference between structures and classes in C++?
36) When do we need to use default arguments in a function?
37) How many types of function ? Exaplain.
38) What is class ?
39) What is object?
40) What do you mean by static variable?
41) What is a friend function?
42) When is a friend function complusory? Give the example.
43) Find out the pure virtual function.
a. virtual void display=0;
b. virtual void display()=0;
c. virtual void display(){};
d. all are wrong
44) Give the advantages of destructors.
45) Give the properties of the constructor.
46) When I write a destructor, do I need to explicitly call the destructors for my member objects?
47) What is a parameterized constructor?
48) What is the use of operator overloading?
49) What is an operator function?
50) How many arguments are required in the definition of an overloaded unary operator?

132

51) which operator you cannot overload?


a. ::
b. : c. > d. >>
52) Can I overload the sizeof operator?
53) In which following type conversion take place in.type conversion Basic To Class.
A)source class
B)destination class
C)source and destination class
54) Overload the * , + and = operators to do the product, sum and assignment of circles. Define the
product of two circles as a circle with X co-ordinate of center as the multiplication of X coordinate of the centers of the two circles. Similarly, calculate the Y co-ordinate of the center.
The resultant circle has a radius equal to the product of the two radius. In a similar way load the
+ operator.
55) Consider a class student that has two fields one for the name and one for the age. Define such
a class and overload the output operator for printing objects of this class. The function should
look like :
main()
{
Student s1(saurabh,22);
cout<< s1;
}
56) How many types of inheritance?
57) What is an abstract class?
58) When do we use the protected visibility specifiers to a class member?
59) What is a virtual base class?
60) When do we make a class virtual?
61) Give an abstract class person which define all persons in an organization including
manager,engineer,worker etc.
62) Define a general fruit class which captures the common behaviour of fruits. Then d efine a
specialized class which categorizes one kind of fruits. The specialized class should be inherited
from fruit class.
63) Define a triangle class. Design a class hierarchy and capture the commonalities of different
geometric objects earlier in the hierarchy. The design should make addition of new geometric
classes easy.

133

Find errors if any or give output for the following programs


1)

What is wrong in the following code?


#include <iostream.h>
void myFunc(int);
int main()
{
unsigned int x=30000, y;
y = myFunc(x);
cout << x: << x << y: << y << \n;
}
void myFunc(int x)
{
return (2*x);
}

2)

When compiled and executed, the following program generates the following erroneous
message: The larger of 10 , 20 is 0 What is the problem ?
#include<iostream.h>
inline void max(int j,int k)
{
cout<< ( j > k ) ? j : k;
}
main()
{
int x=10 , y=20;
cout<<The larger of <<x;
cout<<,<<y<<is ;
max(x,y);
cout<<endl;
return 0;
}

The following code is meaningless, but illustrates the difficulties in writing clear code when side effect are
involved. What is printed?
1.
#include<iostream.h>
int n=7;

134

f(int t)
{
n=(t+1)*(n+1);
}
main()
{
extern int n;
cout<<endl<<The value of n is <<(f(++n),n);
}
2.
#include<iostream.h>
struct foo
{
operator int() { return 1; }
int operator()() { return 2; }
operator()(int) { return 3; }
};
int main()
{
foo bar;
cout<<bar;
cout<<bar();
cout<<bar(1);
}
3.
#include<iostream.h>
class foo
{
public:
char value;
foo(const char x) : value(x) {}
};
class goo : public foo
{
public:
goo(const char y) : foo(y) {}
};
class bar : public foo, public goo
{

135

public:
bar() : foo(A), goo(B) {}
};
int main()
{
bar b;
cout<< b.value;
}
4.
#include<iostream.h>
class foo
{
public:
int value;
virtual foo& operator= (const int v)
{
value=v;
return *this;
}
};
class bar : public foo
{
public:
oprator int() const
{
return value * factor;
}
};
int main()
{
bar<2>x;
x=3;
cout<<x;
}
5.
#include<iostream.h>
class foo
{
public:
136

foo()
{
Name();
}
virtual ~foo()
{
Name();
}
virtual void Name() const
{
cout<< Foo\n;
}
};
class bar : public bar
{
public:
virtual void Name() const
{
cout<<bar\n;
}
};
int main()
{
bar x;
}
6.
class shape
{
public:
virtual void rotate(int angle)=0;
virtual void draw()=0;
protected:
int color,x,y;
};
class Line : public shape
{
public:
void rotate(int angle) {
void draw() { ..}
};

137

..}

class circle : public shape


{
public:
void draw(){.}
};
main()
{
circle c;

}
7.
class A
{
int x;
void display()
{
cout<<x;
}
};
main()
{
A a;
a.display();
}

8.
class A
{
int x;
x()
{
x=9;
}
void display()
{
cout<<x;
}
};
main()
{
A a;
a.display();
138

a.x=8;
a.display();
}
9.
class temp
{
int x;
temp(int y){x=y;}
temp(temp &y){ x=y.x;}
void display()
{
cout<<x;
}
};
main()
{
temp p;p.x=10;r=20;
temp t(p);
t.display();
}
10.
class simple
{
int x;
};
main()
{
simple s;
cout<<s.x;
}
11.
class third
{
public:
void put()
{
cout<<\n Good morning;
}
};
main()

139

{
third t;
cout<<t.put();
}
12.
class test
{
public:
void display()
cout<<\n Hello;
};
main()
{
test t;
t.display();
}
13.
class first
{
int x;
public:
first()
{
x=9;
}
};
main()
{
first f;
f.display();
f.x=8;
f.display();
}

14.
class item
{
140

public :
void printline()
{
int i;
for(i=0;i<10;i++)
cout<<*;
}
};
main()
{
item t1;
cout<<t1.printline();
}
15.
main()
{
int age=30;
cout<<\n Hello friends;
cout<<My age is = age;
}
16.
class first
{
void display()
{
cout<<\n Hello;
}
void display(char a[])
{
cout<<\n Hello <<a;
}
int display()
{
cout<<\n Hello ;
return 8;
}
};

141

main()
{
first f;
f.display();
f.display(saurabh);
cout<<f.display();
}
17.
class friend1
{
int id;
public:
void setId(int h)
{
id=h;
}
friend int getId();
};
int getId()
{
retunr id;
}
main()
{
firend1 f;
f.setId(9);
cout<<f.getId();
}
18.
class friend1
{
int id;
public:
void setId(int h)
{
id=h;
}
friend int getId(friend1 f)
{
return id;
}
142

};
main()
{
firend1 f;
f.setId(9);
cout<<getId();
}
19.
class con1
{
int x;
con1()
{
x=138;
}
public:
void value()
{
cout<<\n x=<<x;
}
};
main()
{
con1 c;
c.display();
}
20.
class con2
{
public:
int id;
con2(int f)
{
id=f;
}
};
main()
{
con2 c(138),c1;
cout<<\n My id=<<c.id;
cout<<\n Your id=<<c1.id;
}

143

21.
class con3
{
public:
con3()
{
cout<<\n No argument constructor ;
}
con3(int y)
{
cout<<\n One argument constructor ;
}
~con3()
{
cout<<\n no argument Destructor ;
}
~con3(int y)
{
cout<<\n One argument Destructor ;
}
};
main()
{
con3 c;
{
con3 c1(8);
}
}
22.
class parent
{
int first;
protected:
int second;
public:
int third;
};
class child
{
public:
child(int i)
{
144

first=i;
second=++i+i;
third=i;
}
void show()
{
cout<<\n First value =<<first;
cout<<\n Second value =<<second;
cout<<\n Third value =<<third;
}
};
main()
{
child c(8);
c.show();
}
23.
class kaka
{
private:
int no;
};
class mama
{
public:
int no;
};
class sister : public kaka , public mama
{
public:
void show()
{
cout<<\n My lucky no =<< no;
}
};
main()
{
sister s;
s.show();
}

145

Contents
OOPs and Basics of C++ ........................................................................................ 1
Need of C++ ........................................................................................................................................ 1
The Three OOP Principles ............................................................................................................... 2
Application of C++ .............................................................................................................................. 3
First C++ Program ............................................................................................................................. 4
Explanation of First C++ Program .................................................................................................. 5
Output in C++ ................................................................................................................................... 6
Data Types ............................................................................................................................................ 7
Variables ................................................................................................................................................ 7
Operators in C++ ................................................................................................................................ 8
Input in C++ ...................................................................................................................................... 8
Manipulators ........................................................................................................................................ 9
Control Structure .............................................................................................................................. 11
The If Statement ............................................................................................................................... 11
Multiple if Statement ....................................................................................................................... 1 3
Switch Statement ............................................................................................................................... 1 7
Loops in C++ ..................................................................................................................................... 1 8

Functions in C++ .................................................................................................... 2 3


Prototype of the Function ............................................................................................................... 2 3
Function Definition ........................................................................................................................... 2 4
The return statement ....................................................................................................................... 2 4
Calling The Function ........................................................................................................................ 2 4
Call by value and Call by reference .............................................................................................. 2 5
Functions with Default Parameters .............................................................................................. 2 7
Function Overloading ...................................................................................................................... 2 9
Inline Functions ................................................................................................................................. 3 2

Classes and Objects............................................................................................... 3 5


Declaration of Class ......................................................................................................................... 3 5
Objects ................................................................................................................................................ 3 6
Scope Resolution operator ............................................................................................................. 4 1
Definition of Member Function Outside of the Class .......................................................... 4 2
Returning Object .............................................................................................................................. 4 5

Constructor and Destructor ................................................................................. 4 7


Constructor ........................................................................................................................................ 4 8
Constructor Overloading ................................................................................................................ 4 9
Destructor ........................................................................................................................................... 5 5
Static Data Members........................................................................................................................ 5 6
Static Member Functions ................................................................................................................ 5 8
Friend Function ................................................................................................................................. 6 0
Friend Class ....................................................................................................................................... 6 3

Operator Overloading ........................................................................................... 6 7


Unary Operator Overloading ......................................................................................................... 6 7
Returning of Object with Unary Operator Overloading.......................................................... 7 0
Binary Operator Overloading ........................................................................................................ 7 1
Return Value with Binary Operator Overloading. .................................................................... 7 3
Passing Object with Binary Operator Overloading .................................................................. 7 3
Returning Object with Binary Operator Overloading. ............................................................ 7 5

Inheritance ............................................................................................................... 7 9
Creation of Derived Class .............................................................................................................. 7 9
Protected member ............................................................................................................................ 8 1
Access Specifier in Derivation ...................................................................................................... 8 2
Overriding Member Functions...................................................................................................... 8 4
Multilevel Inheritance ..................................................................................................................... 8 5
Multiple Inheritance ........................................................................................................................ 8 8
Ambiguity In Multiple Inheritance ............................................................................................... 8 9
Virtual Base Class ............................................................................................................................ 9 0
Execution order of Constructor in Inheritance ......................................................................... 9 2

Pointers .................................................................................................................... 9 7
Need of Pointers ............................................................................................................................... 9 7
Use of Pointer .................................................................................................................................... 9 7
Advantages of using the pointer ................................................................................................... 9 8
Pointer Variable ................................................................................................................................. 9 8
Pointer Arithmetic .......................................................................................................................... 100
Pointers and Arrays ........................................................................................................................ 101
Pointers to Objects ......................................................................................................................... 102
Virtual Functions ............................................................................................................................. 107
Pure Virtual Functions ................................................................................................................... 110

Abstract Classes ............................................................................................................................. 112

File Handling in C++ ........................................................................................... 113


File Class Hierarchy ...................................................................................................................... 114
Types of Files ................................................................................................................................... 114
Opening and Closing a file ........................................................................................................... 115
Opening files using constructor .................................................................................................. 115
Open file with open() function ..................................................................................................... 117
Getting the Right Path ................................................................................................................... 117
Open Mode Bits .............................................................................................................................. 117
Reading and Writing File Character by Character ................................................................. 118
Detecting end-of-file ...................................................................................................................... 119
The write() Function ...................................................................................................................... 119
File Pointers ..................................................................................................................................... 120
The seekp() Function .................................................................................................................... 120
The tellp() Function ....................................................................................................................... 121
The read() Function ........................................................................................................................ 121
The seekg() Function .................................................................................................................... 122
The tellg() Function ....................................................................................................................... 122

Review Questions ................................................................................................. 129

Index
symbols
& 99
.cpp 5
// 6
~ 55

a
access specifier in derivation 82
accessing members 37
address 98, 99
address of operator 98
app 118
array 97, 101
arrow operator 102
ate 118

b
binary operator overloading 71

c
call by reference 25
call by value 25
cascading 6
cin 8
class 7
classes and objects 35
comments 5
constructor 48
constructor 92, 95
constructor with default arguments: 50
control structure 11
copy constructor 51
cout 6

d
data type 7
declaration of class 35
declaration of variable 7
default argument 50

default constructor 95
default parameters 27
definition of member function outside of the cla 42
delete operator 54, 104
derived class 79
destructor 55
difference between class and object 37
do..while loop 21

e
else clause 12
eof() 119
extraction operator 8

f
first c++ program 4
for loop 18
fstream 114
function definition 24
function overloading 29
functions with default parameters 27

g
get() 118

i
i/o operations 113
ifstream 114
in 118
indirection operator 100
inheritance 106
inline functions 32
input in c++ 8
insertion operator 6
interface 113
intermediate base class 86
ios 113
iostream.h 5
istream 113

loops in c++ 18

read() 121
return 24
Returning Object 45

m
main() 5
manipulators 9
multiple if 13
multiple inheritance 88, 93

nested if 14
new operator 53, 104

scope Resolution Operation ( :: ) 43


seekg() 122
seekp() 121
stream 6, 113
Structures 102
Switch Statement 17

objects 36
ofstream 114
OOPs 1
open mode 117
operator overloading 67
operators 8
ostream 113
out 118
Output in C++ 6
Overriding 84

tellg() 122
tellp() 121
trunc 118
Typecasting 99

P
pointer variable 99
Pointers 97
Private 82
Private member 38
Protected member 81
Prototype 23
public 82
public access spicifier 67
public member 37
pure virtual function 112
put() 118

U
Unary Operator Overloading 67

V
virtual 107
virtual base class 90
void 5

W
While Loop 19
write() 119

PREFACE
A few years ago, various fields were researched independently, they never
assisted, interfered or interacted with other researches. Thereafter a few more
years down the line came in the set of INFORMATION TECHNOLOGY which
altered the entire globe. It plugged on all researches scientific and otherwise via
the tool named Internet. Today we are using these computer aided tools to
enhance and represent our business and information in a more appealing and
presentable manner. At the gateway of the 21 st century, the tools and connectivity
of digital age have given us better ways to obtain, share and act on information
in new and remarkable ways.
As a Director of Azure, my dream is to spread this Information technology
through the community to be successful and enterprising IT professionals leading
this industry to a brighter future by developing powerful tools for analysis and
aptly using the information provided by these solutions. I feel that the flow of
Information and knowledge always flow from father to son, like a child learn so
many things from family itself. So, when a father knows about IT he always insist
that his son should learn IT. This way only I think we can end this IT word in
the each corner of the world. This module will be just hit or help you to get
acquire of this technology and spared it through the community.
To achieve this objective we have succeeded to establish well equipped GLSIIT,
Gujarat Institute of Technology (GIT), Institute of Computer Technology (ICT),
H. K. Computer Centre, C. U. Shah Science College Computer Centre, H. A.
College of Commerce Computer Centre, City College Computer Centre, Jyoti
Sangh Computer Centre, Dharamsinh Desai Institute of Commerce Computer
Centre (Nadiad), Shri N. P. Patel Computer Science Centre (Kalol), Mohinaba
Computer Centre, Ahmedabad and are imparting training to more than 3500
students every year. Furthermore it has been a matter of pride that we have
successfully met the milestones on the road to success to impart the best and
latest technology to the students.
I highly appreciate the efforts put in by the staff members of our organization
who have jointly contributed to put together this module. In addition, I would
also like to thank our printers Moti Enterprise.
So, continue your strive to attain success with this module. All the best

Dushyant Joshi
Director

STUDY REFERENCE

OBJECT ORIENTED
PROGRAMMING
USING C++
Prepared by

AZURE Technologies & Information Services Pvt. Ltd.


Ahmedabad
2001 AZURE Technologies & Information Services Pvt. Ltd.

Rev. 1.0/11-12-2001

Potrebbero piacerti anche