C++ Tutorial
C++ Tutorial
purpose,
case-sensitive,
free-form
programming
language
that
supports
procedural, object-oriented, and generic
programming.
C++ is regarded as a middle-level language,
as it comprises a combination of both high-level
and low-level language features.
C++ was developed by Bjarne Stroustrup
starting in 1979 at Bell Labs in Murray Hill, New
Jersey as an enhancement to the C language
and originally named C with Classes but later it
was renamed C++ in 1983.
C++ is a superset of C, and that virtually any
legal C program is a legal C++ program.
Object-Oriented Programming
C++
fully
supports
object-oriented
programming, including the four pillars of
object-oriented development:
Encapsulation
Data hiding
Inheritance
Polymorphism
Standard Libraries
Standard C++ consists of three important parts:
Learning C++
The most important thing to do when learning
C++ is to focus on concepts and not get lost in
language technical details.
The purpose of learning a programming
language is to become a better programmer;
that is, to become more effective at designing
systems
and
at
C++ Identifiers:
A C++ identifier is a name used to identify a
variable, function, class, module, or any other
user-defined item. An identifier starts with a
letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores,
and digits (0 to 9).
C++ does not allow punctuation characters
such as @, $, and % within identifiers. C++ is a
case
sensitive
programming
language.
Thus Manpower and manpower are
two
different identifiers in C++.
Here are
identifiers:
mohd
a_123
myname50
retVal
some
examples
of
acceptable
zara
abc
move_name
_temp
a23b9
C++ Keywords:
The following list shows the reserved words in
C++. These reserved words may not be used
as constant or variable or any other identifier
names.
asm
else
new
this
auto
enum
operator
throw
bool
explicit
private
true
break
export
protected
try
case
extern
public
typedef
catch
false
register
typeid
char
float
reinterpret_ca typenam
st
class
for
return
union
const
friend
short
unsigne
d
const_cast
goto
signed
using
continue
if
sizeof
virtual
default
inline
static
void
delete
int
static_cast
volatile
do
long
struct
wchar_t
double
mutable
switch
while
dynamic_ca namespac
template
st
e
Whitespace in C++:
A line containing only whitespace, possibly with
a comment, is known as a blank line, and C++
compiler totally ignores it.
// Get
return 0;
}
When the above code is compiled, it will
ignore // prints Hello World and final
executable will produce following result:
Hello World
Within a /* and */ comment, // characters have
no special meaning. Within a // comment, /* and
*/ have no special meaning. Thus, you can
"nest" one kind of comment within the other
kind. For example:
/* Comment out printing of Hello
World:
cout << "Hello World"; // prints
Hello World
*/
While doing programming in any programming
language, you need to use various variables to
store various information. Variables are nothing
Keyword
Boolean
bool
Character
char
Integer
int
Floating point
float
void
Wide character
wchar_t
signed
unsigned
short
long
The following table shows the variable type,
how much memory it takes to store the value
memory, and what is maximum and minimum
vaue which can be stored in such type of
variables.
Type
Typical
Typical Range
Bit Width
char
1byte
-127 to 127 or 0 to
255
unsigned
1byte
0 to 255
char
signed
char
1byte
-127 to 127
int
4bytes
-2147483648 to
2147483647
unsigned
int
4bytes
0 to 4294967295
signed int
4bytes
-2147483648 to
2147483647
short int
2bytes
-32768 to 32767
unsigned
short int
Range
0 to 65,535
signed
short int
Range
-32768 to 32767
long int
4bytes
-2,147,483,647 to
2,147,483,647
signed
long int
4bytes
unsigned
long int
4bytes
0 to 4,294,967,295
float
4bytes
digits)
double
8bytes
long
double
8bytes
wchar_t
2 or 4
bytes
1 wide character
of
of
of
of
char : 1
int : 4
short int : 2
long int : 4
Size of float : 4
Size of double : 8
Size of wchar_t : 4
Typedef Declarations:
You can create a new name for an existing type
using typedef. Following is the simple syntax to
define a new type using typedef:
typedef type newname;
For example, the following tells the compiler
that feet is another name for int:
typedef int feet;
Now, the following declaration is perfectly legal
and creates an integer variable called distance:
feet distance;
#include <iostream>
#include <string>
using namespace std;
int main()
{
SmallNumber temperature = 248;
" <<
" <<
for(int i = 0; i <
sizeof(countries) /
sizeof(string); i++)
cout << '\t' <<
countries[i] << endl;
1048
Distance:
390.82
Countries:
Ghana
Angola
Togo
Tunisia
Cote d'Ivoire
Enumerated Types:
An enumerated type declares an optional type
name and a set of zero or more identifiers that
can be used as values of the type. Each
enumerator is a constant whose type is the
enumeration.
To create an enumeration requires the use of
the keyword enum. The general form of an
enumeration type is:
Enum example
#include <iostream.h>
int main()
{
enum
Days{Sunday,Monday,Tuesday,Wednesday,
Thursday,Friday,Saturday};
Days TheDay;
int j;
cout<<"Please enter the day of the week (0
to 6)";
cin>>j;
TheDay = Days(j);
if(TheDay == Sunday || TheDay ==
Saturday)
Local Variables:
Variables that are declared inside a function or
block are local variables. They can be used
only by statements that are inside that function
or block of code. Local variables are not known
to functions outside their own. Following is the
example using local variables:
#include <iostream>
using namespace std;
int main ()
{
// Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables:
Global variables are defined outside of all the
functions, usually on top of the program. The
global variables will hold their value throughout
the lifetime of your program.
A global variable can be accessed by any
function. That is, a global variable is available
char
'\0'
float
double
pointer
NULL
Character literals:
Character literals are enclosed in single quotes.
If the literal begins with L (uppercase only), it is
a wide character literal (e.g., L'x') and should be
stored in wchar_t type of variable . Otherwise,
it is a narrow character literal (e.g., 'x') and can
be stored in a simple variable of char type.
A character literal can be a plain character
(e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
There are certain characters in C++ when they
are proceeded by a back slash they will have
special meaning and they are used to represent
Meaning
\\
\ character
\'
' character
\"
" character
\?
? character
\a
Alert or bell
\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
int main()
{
cout << "Hello\tWorld\n\n";
return 0;
}
When the above code is compiled and
executed, it produces following result:
Hello
World
String literals:
String literals are enclosed in double quotes. A
string contains characters that are similar to
character literals: plain characters, escape
sequences, and universal characters.
You can break a long lines into multiple lines
using string literals and separating them using
whitespaces.
Defining Constants:
There are two simple ways in C++ to define
constants:
#define
Storage Classes:
A storage class defines the scope (visibility)
and life time of variables and/or functions within
a C++ Program. These specifiers precede the
type that they modify. There are following
storage classes which can be used in a C++
Program
auto
register
static
extern
mutable
}
// Function definition
void func( void )
{
static int i = 5; // local
static variable
i++;
std::cout << "i is " << i ;
std::cout << " and count is "
<< count << std::endl;
}
When the above code is compiled and
executed, it produces following result:
i
i
i
i
i
i
i
i
i
i
is
is
is
is
is
is
is
is
is
is
6 and count is 9
7 and count is 8
8 and count is 7
9 and count is 6
10 and count is 5
11 and count is 4
12 and count is 3
13 and count is 2
14 and count is 1
15 and count is 0
int count ;
extern void write_extern();
main()
{
count = 5;
write_extern();
}
Second File: write.cpp
#include <iostream>
extern int count;
void write_extern(void)
{
std::cout << "Count is " <<
count << std::endl;
}
Here extern keyword is being used to declare
count in another file. Now compile these two
files as follows:
$g++ main.cpp write.cpp -o write
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic,
relational, and logical, bitwise, assignment and
other operators one by one.
Arithmetic Operators:
There are following arithmetic
supported by C++ language:
operators
Example
Adds two
operands
A + B will give
30
Subtracts
second
operand from
the first
A - B will give 10
Multiply both
operands
A * B will give
200
Divide
numerator by
de-numerator
B / A will give 2
Modulus
Operator and
B % A will give
remainder of
0
after an integer
division
++
Increment
operator,
increases
integer value
by one
--
Decrement
operator,
decreases
integer value
by one
Relational Operators:
There are following relational
supported by C++ language
operators
Example
==
Checks if the
value of two
operands is
(A == B) is not
equal or not, if
true.
yes then
condition
becomes true.
!=
Checks if the
value of two
operands is
equal or not, if
(A != B) is true.
values are not
equal then
condition
becomes true.
>
Checks if the
value of left
operand is
greater than
(A > B) is not
the value of
true.
right operand,
if yes then
condition
becomes true.
<
Checks if the
value of left
operand is less
than the value
(A < B) is true.
of right
operand, if yes
then condition
becomes true.
>=
Checks if the
value of left
operand is
(A >= B) is not
greater than or
true.
equal to the
value of right
operand, if yes
then condition
becomes true.
<=
Checks if the
value of left
operand is less
than or equal
(A <= B) is
to the value of
true.
right operand,
if yes then
condition
becomes true.
Logical Operators:
There are following logical operators supported
by C++ language
Assume variable A holds 1 and variable B holds
0 then:
Show Examples
Operator Description
&&
Example
||
Called Logical
OR Operator. If
any of the two
operands is
(A || B) is true.
non zero then
condition
becomes true.
Called Logical
NOT Operator.
Use to
reverses the
logical state of
!(A && B) is
its operand. If a
true.
condition is
true then
Logical NOT
operator will
make false.
Bitwise Operators:
Bitwise operator works on bits and perform bit
by bit operation. The truth tables for &, |, and ^
are as follows:
p
p&q
p|q
p^q
A = 0011 1100
B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++
language are listed in the following table.
Assume variable A holds 60 and variable B
holds 13 then:
Show Examples
Operator Description
Example
&
Binary AND
Operator
copies a bit to
the result if it
exists in both
operands.
(A & B) will
give 12 which
is 0000 1100
Binary OR
(A | B) will give
Operator
61 which is
copies a bit if it 0011 1101
exists in either
operand.
Binary XOR
Operator
(A ^ B) will give
copies the bit if
49 which is
it is set in one
0011 0001
operand but
not both.
Binary Ones
Complement
(~A ) will give Operator is
60 which is
unary and has
1100 0011
the effect of
'flipping' bits.
<<
Binary Left
Shift Operator.
The left
A << 2 will give
operands value
240 which is
is moved left by
1111 0000
the number of
bits specified
by the right
operand.
>>
Binary Right
Shift Operator.
The left
operands value A >> 2 will give
is moved right 15 which is
by the number 0000 1111
of bits specified
by the right
operand.
Assignment Operators:
There are following assignment operators
supported by C++ language:
Show Examples
Operator Description
Example
Simple
assignment
operator,
C = A + B will
Assigns values assign value of
from right side A + B into C
operands to left
side operand
+=
Add AND
assignment
operator, It
adds right
C += A is
operand to the equivalent to C
left operand
=C+A
and assign the
result to left
operand
-=
Subtract AND
assignment
operator, It
subtracts right
C -= A is
operand from
equivalent to C
the left
=C-A
operand and
assign the
result to left
operand
*=
Multiply AND
assignment
C *= A is
operator, It
equivalent to C
multiplies right = C * A
operand with
the left
operand and
assign the
result to left
operand
/=
Divide AND
assignment
operator, It
divides left
operand with
the right
operand and
assign the
result to left
operand
%=
Modulus AND
assignment
operator, It
takes modulus C %= A is
using two
equivalent to C
operands and = C % A
assign the
result to left
operand
C /= A is
equivalent to C
=C/A
<<=
C <<= 2 is
same as C = C
<< 2
>>=
&=
Bitwise AND
assignment
operator
C &= 2 is same
as C = C & 2
^=
bitwise
exclusive OR
and
assignment
operator
C ^= 2 is same
as C = C ^ 2
|=
bitwise
inclusive OR
and
assignment
operator
C |= 2 is same
as C = C | 2
Misc Operators:
Description
sizeof
Conditional operator. If
Condition ? Condition is true ? then it
X:Y
returns value X : otherwise
value Y
&
Operators
Precedence in
C++:
Operator precedence determines the grouping
of terms in an expression. This affects how an
Associativity
Postfix
Unary
+ - ! ~ ++ - (type)* &
Right to left
sizeof
Multiplicative * / %
Left to right
Additive
Left to right
+-
Shift
<< >>
Left to right
Relational
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
Left to right
Bitwise OR
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
= += -= *=
/= %=>>=
<<= &= ^=
|=
Right to left
Comma
Left to right
while loop
Repeats a statement or
group of statements while a
given condition is true. It
tests the condition before
executing the loop body.
for loop
Execute a sequence of
statements multiple times
and abbreviates the code
that manages the loop
variable.
do...while
loop
nested
loops
Loop Control
Statements:
Terminates
the loop or switch statement
and transfers execution to
the statement immediately
following the loop or switch.
continue
statement
goto
statement
The Infinite
Loop:
A loop becomes infinite loop if a condition never
becomes false. The for loop is traditionally
used for this purpose. Since none of the three
expressions that form the for loop are required,
you can make an endless loop by leaving the
conditional expression empty.
#include <iostream>
using namespace std;
int main ()
{
for( ; ; )
{
printf("This loop will run
forever.\n");
}
return 0;
}
When the conditional expression is absent, it is
assumed to be true. You may have an
initialization and increment expression, but C++
programmers more commonly use the for(;;)
construct to signify an infinite loop.
NOTE: You can terminate an infinite loop by
pressing Ctrl + C keys.
Decision making structures require that the
programmer specify one or more conditions to
be evaluated or tested by the program, along
with a statement or statements to be executed if
the condition is determined to be true, and
optionally, other statements to be executed if
the condition is determined to be false.
Following is the general from of a typical
decision making structure found in most of the
programming languages:
Description
if statement
An if statement consists of
a boolean expression
followed by one or more
statements.
if...else
statement
An if statement can be
followed by an optional
else statement, which
executes when the
boolean expression is
false.
switch
statement
nested if
statements
The ? :
Operator:
We have covered conditional operator ? : in
previous chapter which can be used to
replace if...elsestatements. It has the following
general form:
Exp1 ? Exp2 : Exp3;
Defining a
Function:
The general form of a C++ function definition is
as follows:
return_type function_name(
parameter list )
{
body of the function
}
Example:
Following is the source code for a function
called max().
This
function
takes
two
parameters num1 and num2 and returns the
maximum between the two:
// function returning the max
between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Function
Declarations:
A function declaration tells the compiler about
a function name and how to call the function.
The actual body of the function can be defined
separately.
A function declaration has the following parts:
return_type function_name(
parameter list );
For the above defined function max(), following
is the function declaration:
int max(int num1, int num2);
Parameter names are not importan in function
declaration only their type is required, so
following is also valid declaration:
int max(int, int);
Calling a
Function:
While creating a C++ function, you give a
definition of what the function has to do. To use
a function, you will have to call or invoke that
function.
When a program calls a function, program
control is transferred to the called function. A
called function performs defined task and when
its return statement is executed or when its
function-ending closing brace is reached, it
returns program control back to the main
program.
}
// function returning the max
between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
}
return result;
Function
Arguments:
If a function is to use arguments, it must declare
variables that accept the values of the
arguments. These variables are called
the formal parameters of the function.
The formal parameters behave like other local
variables inside the function and are created
upon entry into the function and destroyed upon
exit.
While calling a function, there are two ways that
arguments can be passed to a function:
Call Type
Description
Call by
value
Call by
pointer
Default
Values for
Parameters:
When you define a function you can specify a
default value for for each of the last parameters.
This value will be used if the corresponding
argument is left blank when calling to the
function.
This is done by using the assignment operator
and assigning values for the arguments in the
function definition. If a value for that parameter
is not passed when the function is called, the
default given value is used, but if a value is
return (result);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
// calling a function to add the
values.
result = sum(a, b);
Defining
Numbers in
C++:
You have already defined numbers in various
examples given in previous chapters. Here is
another consolidated example to define various
types of numbers in C++:
#include <iostream>
using namespace std;
int main ()
{
// number definition:
short s;
int
i;
long
l;
float f;
double d;
// number assignments;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
// number printing;
cout << "short s :"
endl;
cout << "int
i :"
endl;
cout << "long
l :"
endl;
cout << "float f :"
endl;
cout << "double d :"
endl;
return 0;
}
<< s <<
<< i <<
<< l <<
<< f <<
<< d <<
s
i
l
f
d
:10
:1000
:1000000
:230.47
:30949.4
Math
Operations in
C++:
In addition to the various functions you can
create, C++ also includes some useful functions
you can use. These functions are available in
standard C and C++ libraries and called builtin functions. These are functions that can be
included in your program and then use.
double cos(double);
This function takes an angle (as a
double) and returns the cosine.
double sin(double);
This function takes an angle (as a
double) and returns the sine.
double tan(double);
This function takes an angle (as a
double) and returns the tangent.
double log(double);
This function takes a number and
returns the natural log of that
number.
double sqrt(double);
You pass this function a number and
it gives you this square root.
int abs(int);
This function returns the absolute
value of an integer that is passed to
it.
double fabs(double);
This function returns the absolute
value of any decimal number passed
to it.
10
double floor(double);
Finds the integer which is less than
or equal to the argument passed to
it.
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
// number definition:
short s = 10;
int
i = -1000;
long
l = 100000;
float f = 230.47;
double d = 200.374;
// mathematical operations;
cout << "sin(d) :" << sin(d) <<
endl;
cout << "abs(i) :" << abs(i) <<
endl;
cout << "floor(d) :" << floor(d)
<< endl;
cout << "sqrt(f) :" << sqrt(f)
<< endl;
cout << "pow( d, 2) :" << pow(d,
2) << endl;
return 0;
}
When the above code is compiled and
executed, it produces following result:
sign(d) :-0.634939
abs(i) :1000
floor(d) :200
sqrt(f) :15.1812
pow( d, 2 ) :40149.7
Random
Numbers in
C++:
There are many cases where you will wish to
generate a random number. There are actually
two functions you will need to know about
random number generation. The first is rand(),
this function will only return a pseudo random
/* generate 10
random numbers.
j= rand();
cout <<" Random Number : " <<
j << endl;
}
return 0;
}
When the above code is compiled and
executed, it produces following result:
Random
Random
Random
Random
Random
Random
Random
Random
Random
Random
Number
Number
Number
Number
Number
Number
Number
Number
Number
Number
:
:
:
:
:
:
:
:
:
:
1748144778
630873888
2134540646
219404170
902129458
920445370
1319072661
257938873
1256201101
580322989
Declaring
Arrays:
Initializing
Arrays:
You can initialize C++ array elements either
one by one or using a single statement as
follows:
Accessing
Array
Elements:
An element is accessed by indexing the array
name. This is done by placing the index of the
element within square brackets after the name
of the array. For example:
double salary = balance[9];
The above statement will take 10th element
from the array and assign the value to salary
variable. Following is an example which will use
all the above mentioned three concepts viz.
declaration, assignment and accessing arrays:
#include <iostream>
C++ Arrays in
Detail:
Arrays are important to C++ and should need
lots of more detail. There are following few
important concepts which should be clear to a
C++ programmer:
Concept
Description
Multidimensional
arrays
C++ supports
multidimensional arrays.
The simplest form of the
multidimensional array is
the two-dimensional
array.
Pointer to an
array
Passing arrays
to functions
Return array
from functions
TwoDimensional
Arrays:
The simplest form of the multidimensional array
is the two-dimensional array. A two-dimensional
array is, in essence, a list of one-dimensional
arrays. To declare a two-dimensional integer
array of size x,y you would write something as
follows:
type arrayName [ x ][ y ];
Where type can be any valid C++ data type
and arrayName will be a valid C++ identifier.
A two dimensional array can be think as a table
which will have x number of rows and y number
of columns. A 2-dimentional array a which
contains three rows and four columns can be
shown as below:
Initializing
TwoDimensional
Arrays:
Multidimensioned arrays may be initialized by
specifying bracketed values for each row.
Accessing
Two-
Dimensional
Array
Elements:
An element in 2-dimensional array is accessed
by using the subscripts ie. row index and
column index of the array. For example:
int val = a[2][3];
The above statement will take 4th element from
the 3rd row of the array. You can verify it in the
above digram.
#include <iostream>
using namespace std;
int main ()
{
0
0
1
2
2
a[2][1]:
a[3][0]:
a[3][1]:
a[4][0]:
a[4][1]:
4
3
6
4
8
C++ Class
Definitions:
When you define a class, you define a blueprint
for a data type. This doesn't actually define any
data, but it does define what the class name
means, that is, what an object of the class will
consist of and what operations can be
performed on such an object.
A
class
definition
starts
with
the
keyword class followed by the class name; and
the class body, enclosed by a pair of curly
braces. A class definition must be followed
either by a semicolon or a list of declarations.
For example we defined the Box data type
using the keyword class as follows:
class Box
{
public:
double length;
// Length of
a box
Define C++
Objects:
A class provides the blueprints for objects, so
basically an object is created from a class. We
declare objects of a class with exactly the same
sort of declaration that we declare variables of
// Declare Box1
// Declare Box2
Accessing the
Data
Members:
The public data members of objects of a class
can be accessed using the direct member
access operator (.). Let us try following example
to make the things clear:
#include <iostream>
// Length of
// Breadth
// Height of
int main( )
{
Box Box1;
// Declare Box1
of type Box
Box Box2;
// Declare Box2
of type Box
double volume = 0.0;
//
Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height *
Box1.length * Box1.breadth;
cout << "Volume of Box1 : " <<
volume <<endl;
// volume of box 2
volume = Box2.height *
Box2.length * Box2.breadth;
cout << "Volume of Box2 : " <<
volume <<endl;
return 0;
}
When the above code is compiled and
executed, it produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Description
Class member
functions
A member function of a
class is a function that
has its definition or its
prototype within the
class definition like any
other variable.
Class access
modifiers
or protected. By default
members would be
assumed as private.
Constructor &
destructor
A class constructor is a
special function in a
class that is called when
a new object of the class
is created. A destructor
is also a special function
which is called when
created object is
deleted.
C++ copy
constructor
C++ friend
A friend function is
functions
C++ inline
functions
Pointer to C++
classes
A pointer to a class is
done exactly the same
way a pointer to a
structure is. In fact a
class is really just a
structure with functions
in it.
Both data members and
Static members function members of a
of a class
class can be declared as
static.
int data1;
float data2;
void int_data(int d){
data1=d;
cout<<"Number: "<<data1;
}
float float_data(){
cout<<"\nEnter data: ";
cin>>data2;
return data2;
}
};
int main(){
temp obj1, obj2;
obj1.int_data(12);
cout<<"You entered
"<<obj2.float_data();
return 0;
}
Output:
Number: 12
Enter data: 12.43
You entered: 12.43
Explanation of Program
In this program, two data members data1 and data2 and
two member function int_data() and float_data() are
defined under temp class. Two objects obj1 and obj2 of
that class are declared. Function int_data() for the obj1 is
5
Box Box1;
Box
Box Box2;
Box
Both of the objects Box1 and Box2 will have their own
copy of data members.
Accessing the Data Members:
The public data members of objects of a class can be
accessed using the direct member access operator (.). Let
us try following example to make the things clear:
#include <iostream>
using namespace std;
class Box
{
public:
double length;
double breadth;
double height;
};
int main( )
{
Box Box1;
//Box
Box Box2;
//Box
// Length of a box
// Breadth of a box
// Height of a box
// Store the
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length *
Box1.breadth;
cout << "Volume of Box1 : " << volume
<<endl;
// volume of box 2
volume = Box2.height * Box2.length *
Box2.breadth;
cout << "Volume of Box2 : " << volume
<<endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560
8
Description
Class member
functions
Class access
modifiers
Constructor &
destructor
A class constructor is a
special function in a class that
is called when a new object of
the class is created. A
9
C++ copy
constructor
C++ friend
functions
Pointer to C++
classes
private:
double width;
};
// Member functions definitions
double Box::getWidth(void)
{
return width ;
}
void Box::setWidth( double wid )
{
width = wid;
}
// Main function for the program
int main( )
{
Box box;
// set box length without member
function
box.length = 10.0; // OK: because length
is public
cout << "Length of box : " << box.length
<<endl;
// set box width without member function
// box.width = 10.0; // Error: because
width is private
15
};
class SmallBox:Box // SmallBox is the
derived class.
{
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};
// Member functions of child class
double SmallBox::getSmallWidth(void)
{
return width ;
}
void SmallBox::setSmallWidth( double wid )
{
width = wid;
}
// Main function for the program
int main( )
{
SmallBox box;
// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<<
box.getSmallWidth() << endl;
17
return 0;
}
When the above code is compiled and executed, it
produces following result:
Width of box : 5
A member function of a class is a function that has its
definition or its prototype within the class definition like any
other variable. It operates on any object of the class of
which it is a member, and has access to all the members
of a class for that object.
Let us take previously defined class to access the
members of the class using a member function instead of
directly accessing them:
class Box
{
public:
double
box
double
a box
double
box
double
volume
};
length;
// Length of a
breadth;
// Breadth of
height;
// Height of a
18
19
// Length of a
// Breadth of
// Height of a
20
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume
<<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume
<<endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560
The Class Constructor:
22
Constructor Example
/*Source Code to demonstrate the working of
constructor in C++ Programming */
/* This program calculates the area of a
rectangle and displays it. */
#include <iostream>
using namespace std;
class Area
{
private:
int length;
int breadth;
public:
Area(): length(5), breadth(2){ }
/* Constructor */
void GetLength()
{
cout<<"Enter length and breadth
respectively: ";
cin>>length>>breadth;
}
int AreaCalculation() { return
(length*breadth); }
void DisplayArea(int temp)
{
cout<<"Area: "<<temp;
}
};
int main()
{
24
Area A1,A2;
int temp;
A1.GetLength();
temp=A1.AreaCalculation();
A1.DisplayArea(temp);
cout<<endl<<"Default Area when value is
not taken from user"<<endl;
temp=A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
Explanation
In this program, a class of name Area is created to
calculate the area of a rectangle. There are two data
memberslength and breadth. A constructor is defined
which initializes length to 5 and breadth to 2. And, we
have three additional member functions GetLength(),
AreaCalculation() and DisplayArea() to get length from
user, calculate the area and display the area respectively.
When, objects A1 and A2 are created then, the length and
breadth of both objects are initialized to 5 and 2
respectively because of the constructor. Then the member
function GetLength() is invoked which takes the value
oflength and breadth from user for object A1. Then, the
area for the object A1 is calculated and stored in
variable tempby calling AreaCalculation() function. And
finally, the area of object A1 is displayed. For object A2,
25
no data is asked from the user. So, the value of length will
be 5 and breadth will be 2. Then, the area for A2 is
calculated and displayed which is 10.
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor
};
private:
double length;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " <<
line.getLength() <<endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
Object is being created
Length of line : 6
Parameterized Constructor:
A default constructor does not have any paramter but if
you need a constructor can have parameters. This helps
you to assign initial value to an object at the time of its
creation as shown in the following example:
27
Area A1,A2(2,1);
int temp;
cout<<"Default Area when no argument is
passed."<<endl;
temp=A1.AreaCalculation();
A1.DisplayArea(temp);
cout<<"Area when (2,1) is passed as
arguement."<<endl;
temp=A2.AreaCalculation();
A2.DisplayArea(temp);
return 0;
}
For object A1, no argument is passed. Thus, the
constructor with no argument is invoked which
initializes length to 5 and breadth to 2. Hence, the area of
object A1 will be 10. For object A2, 2 and 1 is passed as
argument. Thus, the constructor with two argument is
called which initializes length to l(2 in this case)
and breadth to b(1 in this case.). Hence the area of
object A2 will be 2.
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
29
Line(double len);
constructor
};
// This is the
private:
double length;
length = len;
}
double Line::getLength( void )
{
return length;
}
// Main function for the program
int main( )
{
Line line;
// set line length
line.setLength(6.0);
cout << "Length of line : " <<
line.getLength() <<endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
Object is being created
Length of line : 6
Object is being deleted
33
34
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len );
simple constructor
Line( const Line &obj);
constructor
~Line();
destructor
};
//
// copy
//
private:
int *ptr;
{
cout << "Copy constructor allocating
ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
void display(Line obj)
{
cout << "Length of line : " <<
obj.getLength() <<endl;
}
// Main function for the program
int main( )
{
Line line(10);
display(line);
return 0;
36
}
When the above code is compiled and executed, it
produces following result:
Normal constructor allocating ptr
Copy constructor allocating ptr.
Length of line: 10
Freeing memory!
Freeing memory!
Let us see the same example but with a small change to
create another object using existing object of the same
type:
#include <iostream>
using namespace std;
class Line
{
public:
int getLength( void );
Line( int len );
simple constructor
Line( const Line &obj);
constructor
~Line();
destructor
private:
int *ptr;
37
//
// copy
//
};
// Member functions definitions including
constructor
Line::Line(int len)
{
cout << "Normal constructor allocating
ptr" << endl;
// allocate memory for the pointer;
ptr = new int;
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "Copy constructor allocating
ptr." << endl;
ptr = new int;
*ptr = *obj.ptr; // copy the value
}
Line::~Line(void)
{
cout << "Freeing memory!" << endl;
delete ptr;
}
int Line::getLength( void )
{
return *ptr;
}
38
Freeing memory!
Freeing memory!
One of the important concept of OOP is data hiding, i.e., a
nonmember function cannot access an object's private or
protected data. But, sometimes this restriction may force
programmer to write long and complex codes. So, there is
mechanism built in C++ programming to access private or
protected data from non-member function which is friend
function and friend class.
friend Function in C++
If a function is defined as a friend function then, the
private and protected data of class can be accessed from
that function. The complier knows a given function is a
friend function by its keyword friend. The declaration of
friend function should be made inside the body of class
(can be anywhere inside class either in private or public
section) starting with keyword friend.
class class_name
{
...... ....
........
friend return_type function_name(argument/s);
......
....
........
}
A friend function of a class is defined outside that class's
scope but it has the right to access all private and
40
public:
Distance(): meter(0){ }
friend int func(Distance);
//friend function
};
int func(Distance d)
//function
definition
{
d.meter=5;
//accessing private
data from non-member function
return d.meter;
}
int main()
{
Distance D;
cout<<"Distace: "<<func(D);
return 0;
}
Output
Distance: 5
Here, friend function func() is declared inside Distance
class. So, the private data can be accessed from this
function.
Though this example gives you what idea about the
concept of friend function, this program doesn't give you
idea about when friend function is helpful.
42
43
}
// Main function for the program
int main( )
{
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the
wdith.
printWidth( box );
return 0;
}
When the above code is compiled and executed, it
produces following result:
Width of box : 10
Example to operate on Objects of two Different class using
friend Function
#include <iostream>
using namespace std;
45
class B;
// forward declaration
class A {
private:
int data;
public:
A(): data(12){ }
friend int func(A , B);
//friend
function Declaration
};
class B {
private:
int data;
public:
B(): data(1){ }
friend int func(A , B); //friend
function Declaration
};
int func(A d1,B d2)
/*Function func() is the friend function of
both classes A and B. So, the private data
of both class can be accessed from this
function.*/
{
return (d1.data+d2.data);
}
int main()
{
A a;
B b;
cout<<"Data: "<<func(a,b);
return 0;
46
}
In this program, classes A and B has declared func() as a
friend function. Thus, this function can access private data
of both class. In this program, two objects of two different
class A and B are passed as an argument to friend
function. Thus, this function can access private and
protected data of both class. Here, func() function adds
private data of two objects and returns it to main function.
To work this program properly, a forward declaration of a
class should be made as in above example(forward
declaration of class B is made). It is because class B is
referenced from class A using code: friend int func(A , B);.
So, class A should be declared before class B to work
properly.
friend Class in C++ Programming
Similarly like, friend function. A class can be made a friend
of another class using keyword friend. For example:
........ ..... ........
class A{
friend class B;
// class B is a
friend class
..... ..... .....
}
class B{
..... ..... .....
}
47
This pointer in C
Every object in C++ has access to its own address
through an important pointer called this pointer.
Thethis pointer is an implicit parameter to all member
functions. Therefore, inside a member function, this may
be used to refer to the invoking object.
Friend functions do not have a this pointer, because
friends are not members of a class. Only member
functions have a this pointer.
Let us try the following example to understand the concept
of this pointer:
#include <iostream>
using namespace std;
class Box
{
public:
// Constructor definition
50
// Declare
// Declare
if(Box1.compare(Box2))
{
cout << "Box2 is smaller than Box1"
<<endl;
}
else
{
cout << "Box2 is equal to or larger
than Box1" <<endl;
}
return 0;
}
When the above code is compiled and executed, it
produces following result:
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1
Pointer in C++
A pointer to a C++ class is done exactly the same way as
a pointer to a structure and to access members of a
pointer to a class you use the member access operator > operator, just as you do with pointers to structures. Also
as with all pointers, you must initialize the pointer before
using it.
52
53
int main(void)
{
Box Box1(3.3, 1.2, 1.5);
box1
Box Box2(8.5, 6.0, 2.0);
box2
Box *ptrBox;
pointer to a class.
// Declare
// Declare
// Declare
54
Constructor called.
Constructor called.
Volume of Box1: 5.94
Volume of Box2: 102
Static Member
We can define class members static using static keyword.
When we declare a member of a class as static it means
no matter how many objects of the class are created,
there is only one copy of the static member.
A static member is shared by all objects of the class. All
static data is initialized to zero when the first object is
created, if no other initialization is present. We can't put it
in the class definition but it can be initialized outside the
class as done in the following example by redeclaring the
static variable, using the scope resolution operator :: to
identify which class it belongs to.
Let us try the following example to understand the concept
of static data members:
#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
// Constructor definition
55
// Declare
// Declare
57
}
double Volume()
{
return length * breadth * height;
}
static int getCount()
{
return objectCount;
}
private:
double length;
// Length of a box
double breadth;
// Breadth of a
box
double height;
// Height of a box
};
// Initialize static member of class Box
int Box::objectCount = 0;
int main(void)
{
// Print total number of objects before
creating object.
cout << "Inital Stage Count: " <<
Box::getCount() << endl;
Box Box1(3.3, 1.2, 1.5);
box1
Box Box2(8.5, 6.0, 2.0);
box2
59
// Declare
// Declare
63
#include <iostream>
using namespace std;
class Rectangle
{
protected:
float length, breadth;
public:
Rectangle(): length(0.0),
breadth(0.0)
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}
};
/* Area class is derived from base class
Rectangle. */
class Area : public Rectangle
{
public:
float calc()
{
return length*breadth;
}
};
64
Accessbility
Accessible from
own class ?
yes
yes
yes
Accessible from
dervied class ?
no
yes
yes
Accessible
outside dervied
class ?
no
no
yes
Type of Inheritance:
When deriving a class from a base class, the base class
may
be
inherited
through public,
protected or
private inheritance. The type of inheritance is specified by
the access-specifier as explained above.
We
hardly
use protected or private inheritance
but public inheritance is commonly used. While using
different type of inheritance, following rules are applied:
Public Inheritance: When deriving a class from
a public base class, public members of the base class
become public members
of
the
derived
class
and protected members
of
the
base
class
become protected members of the derived class. A base
class's private members are never accessible directly
from a derived class, but can be accessed through calls to
the publicand protected members of the base class.
67
Protected
Inheritance: When
deriving
from
a protected base class, public and protectedmembers of
the base class become protected members of the derived
class.
Private Inheritance: When deriving from a private base
class, public and protected members of the base class
become private members of the derived class.
Things to remember while Using Public, Protected and
Private Inheritance
1. Protected and public members(data and function) of a
base class are accessible from a derived class(for all
three: public, protected and private inheritance).
2. Objects of derived class with private and protected
inheritance cannot access any data member of a base
class.
3. Objects of derived class with public inheritance can
access only public member of a base class.
68
69
Accessibility
Accessible from
own class?
yes
yes
yes
Accessible from
dervied class?
no
yes
yes
Accessible
outside dervied
class?
no
no
yes
Accessible from
own class?
yes
yes
yes
Accessible from
dervied class?
no
yes
yes
Accessible
outside dervied
class?
no
no
no
70
Accessible from
own class?
yes
yes
yes
Accessible from
dervied class?
no
yes
yes
Accessible
outside dervied
class?
no
no
no
int main(void)
{
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total area: " << Rect.getArea()
<< endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
Total area: 35
Multilevel Inheritance and Multiple Inheritance in C++
Programming
Levels of Inheritance
In C++ programming, a class be can derived from a
derived class which is known as multilevel inhertiance. For
example:
class A
73
int main()
{
C c;
c.display();
return 0;
}
Output
Base class content.
Explanation of Program
In this program, class B is derived from A and C is derived
from B. An object of class C is defined in main( )function.
When the display( ) function is called, display( ) in
class A is executed because there is no display( ) function
in C and B. The program first looks for display( ) in class C
first but, can't find it. Then, looks in B because C is
derived from B. Again it can't find it. And finally looks it
in A and executes the codes inside that function.
If there was display( ) function in C too, then it would
have override display( ) in A because of member function
overriding.
Multiple Inheritance in C++
In C++ programming, a class can be derived from more
than one parents. For example: A class Rectangle is
derived from base classes Area and Circle.
75
return 2*(l+b);
}
};
/* Rectangle class is derived from classes
Area and Perimeter. */
class Rectangle : private Area, private
Perimeter
{
private:
float length, breadth;
public:
Rectangle() : length(0.0),
breadth(0.0) { }
void get_data( )
{
cout<<"Enter length: ";
cin>>length;
cout<<"Enter breadth: ";
cin>>breadth;
}
float area_calc()
{
/* Calls area_calc() of class Area
and returns it. */
return
Area::area_calc(length,breadth);
}
77
float peri_calc()
{
/* Calls peri_calc() function of
class Perimeter and returns it. */
return
Perimeter::peri_calc(length,breadth);
}
};
int main()
{
Rectangle r;
r.get_data();
cout<<"Area = "<<r.area_calc();
cout<<"\nPerimeter = "<<r.peri_calc();
return 0;
}
Output
Enter length: 5.1
Enter breadth: 2.3
Area = 11.73
Perimeter = 14.8
Note: This program is intended to give you idea on how
multiple inheritance works rather than the condition in
which multiple inheritance is used.
78
};
public:
int getArea()
{
return (width * height);
}
int main(void)
{
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
// Print the area of the object.
cout << "Total area: " << Rect.getArea()
<< endl;
// Print the total cost of painting
cout << "Total paint cost: $" <<
Rect.getCost(area) << endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
82
Total area: 35
Total paint cost: $2450
C++ Overloading (Operator and Function)
C++ allows you to specify more than one definition for
a function name or an operator in the same scope, which
is
called function
overloading and operator
overloading respectively.
An overloaded declaration is a declaration that had been
declared with the same name as a previously declared
declaration in the same scope, except that both
declarations have different arguments and obviously
different definition (implementation).
When you call an overloaded function or operator, the
compiler determines the most appropriate definition to use
by comparing the argument types you used to call the
function or operator with the parameter types specified in
the definitions. The process of selecting the most
appropriate overloaded function or operator is
called overload resolution.
Function overloading in C++:
You can have multiple definitions for the same function
name in the same scope. The definition of the function
must differ from each other by the types and/or the
number of arguments in the argument list. You can not
overload function declarations that differ only by return
type.
83
void print(char* c) {
cout << "Printing character: " << c
<< endl;
}
};
int main(void)
{
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
84
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
When the above code is compiled and executed, it
produces following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Operators overloading in C++:
C++ Programming Operator Overloading
The meaning of operators are already defined and fixed
for basic types like: int, float, double etc in C++ language.
For example: If you want to add two integers then, +
operator is used. But, for user-defined types(like: objects),
you can define the meaning of operator, i.e, you can
redefine the way that operator works. For example: If
there are two objects of a class that contain string as its
data member, you can use + operator to concatenate two
strings. Suppose, instead of strings if that class contains
integer data member, then you can use + operator to add
integers. This feature in C++ programming that allows
programmer to redefine the meaning of operator when
they operate on class objects is known as operator
overloading.
85
86
Count: 6
Explanation
In this program, a operator function void operator ++
() is defined(inside class temp), which is invoked when ++
operator operates on the object of type temp. This
function will increase the value of count by 1.
Things to remember while using Operator overloading in
C++ language
1. Operator overloading cannot be used to change the
way operator works on built-in types. Operator
overloading only allows to redefine the meaning of
operator for user-defined types.
2. There are two operators assignment operator(=) and
address operator(&) which does not need to be
overloaded. Because these two operators are already
overloaded in C++ library. For example:
If obj1 and obj2are two objects of same class then,
you can use code obj1=obj2; without overloading =
operator. This code will copy the contents object
of obj2 to obj1. Similarly, you can use address
operator directly without overloading which will return
the address of object in memory.
3. Operator overloading cannot change the precedence
of operators and associativity of operators. But, if you
88
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box
objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length +
b.length;
box.breadth = this->breadth +
b.breadth;
91
box.height = this->height +
b.height;
return box;
}
private:
double length;
// Length of a
box
double breadth;
// Breadth of a
box
double height;
// Height of a
box
};
// Main function for the program
int main( )
{
Box Box1;
// Declare Box1
of type Box
Box Box2;
// Declare Box2
of type Box
Box Box3;
// Declare Box3
of type Box
double volume = 0.0;
// Store the
volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
92
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume
<<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume
<<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume
<<endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Overloadable/Non-overloadableOperators:
93
&
<
>
<=
>=
++
--
<<
>>
==
!=
&&
||
+=
-=
/=
%=
^=
&=
|=
*=
<<=
>>=
[]
()
->
->*
new
new []
delete
delete
[]
.*
?:
94
95
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
};
int main()
{
Distance D1(11, 10), D2(-5, 11);
-D1;
negation
D1.displayDistance();
-D2;
negation
D2.displayDistance();
// apply
// display D1
// apply
// display D2
return 0;
}
When the above code is compiled and executed, it
produces following result:
F: -11 I:-10
F: 5 I:-11
The unary operators take two arguments and following are
the examples of Binary operators. You use binary
operators very frequently like addition (+) operator,
subtraction (-) operator and division (/) operator.
97
// Length of a box
// Breadth of a box
// Height of a box
double getVolume(void)
{
return length * breadth * height;
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
98
}
// Overload + operator to add two Box
objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth +
b.breadth;
box.height = this->height + b.height;
return box;
}
};
// Main function for the program
int main( )
{
Box Box1;
// Declare Box1
of type Box
Box Box2;
// Declare Box2
of type Box
Box Box3;
// Declare Box3
of type Box
double volume = 0.0;
// Store the
volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
99
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume
<<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume
<<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume
<<endl;
return 0;
}
When the above code is compiled and executed, it
produces following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
100
if( D1 < D2 )
{
cout << "D1 is less than D2 " <<
endl;
}
else
{
cout << "D2 is less than D1 " <<
endl;
}
return 0;
}
When the above code is compiled and executed, it
produces following result:
D2 is less than D1
The word polymorphism means having many forms.
Typically, polymorphism occurs when there is a hierarchy
of classes and they are related by inheritance.
C++ polymorphism means that a call to a member function
will cause a different function to be executed depending
on the type of object that invokes the function.
Consider the following example where a base class has
been derived by other two classes:
#include <iostream>
using namespace std;
103
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :"
<<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :"
<<endl;
return (width * height);
}
};
class Triangle: public Shape{
104
public:
Triangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
cout << "Rectangle class area :"
<<endl;
return (width * height / 2);
}
};
// Main function for the program
int main( )
{
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// store the address of Rectangle
shape = &rec;
// call rectangle area.
shape->area();
// store the address of Triangle
shape = &tri;
// call triangle area.
shape->area();
return 0;
}
105
#include <iostream>
using namespace std;
class B
{
public:
void display()
108
{ cout<<"Content of base
class.\n"; }
};
class D : public B
{
public:
void display()
{ cout<<"Content of derived
class.\n"; }
};
int main()
{
B *b;
D d;
b->display();
d = &b;
/* Address of object d in
pointer variable */
d->display();
return 0;
}
Note: An object(either normal or pointer) of derived class
is type compatible with pointer to base class. So, b =
&d; is allowed in above program.
Output
Content of base class.
Content of base class.
109
void display()
{ cout<<"Content of first derived
class.\n"; }
};
class D2 : public B
{
public:
void display()
{ cout<<"Content of second derived
class.\n"; }
};
int main()
{
B *b;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this
code here because the function of base
class is virtual. */
b = &d1;
b->display();
/* calls display() of
class derived D1 */
b = &d2;
b->display();
/* calls display() of
class derived D2 */
return 0;
}
111
Output
Content of first derived class.
Content of second derived class.
After the function of base class is made virtual, code b>display( ) will call the display( ) of the derived class
depending upon the content of pointer.
In this program, display( ) function of two different classes
are called with same code which is one of the example of
polymorphism in C++ programming using virtual
functions.
112