Unit 3
Unit 3
Vorking ith
Inherit
Inheritance in C++, Pointers to Objects, Input-Output and Manipulators in C++ 107
Chapter 3
Class C
Class B
Class C
class (class
B C
class
D
(v)
Hybrid Inheritance
3.1.3 Public, Private and Protected Inheritance:
Base Class and Derived Class:
Employee
Program to demonstrate the accessibility of the Base class members Inside a Derived
class:
#include<iostream.h>
#includecconio.h>
class base
int b_pri;
protected:
int b_pro;
public:
int b_pub;
void setCO
b_pri-1;
bpro=2;
bpub-3
int get pri)
return b-pri;
Class derived:publ1ic
base
public:
void show)
private member not // directly
get-pri); 77
jaccessible member: "<<
le. NPrivate
Vipul'sM Object Oriented rOgramming
Programmi
withc WoIk
|}
void main()
clrscr():
derived d;
d.set
d.show);
getch):
Output:
Private member: 1
2
Protected member:
Public member: 3 members (public, protected and private)o p
inherits all the
Note that the derived class
access only the public and protected member inE
the base class, however, it can directly protected and public member
are accessed indirectly using the
The private members
functions of the base class.
Table 1
Accessibility of Base Class Members
Base Class Accessibility by objects of
|
Accessibility Inside
Members Base Class Members the DerivedClass
Public Accessible Accessible
Protected Not Accessible Accessible
Private Not Accessible Not Accessible
Access Specifier of the Base Class:
t
The access specifier of the base class in the derived class definition determines
way the derived class inherits the base class. It determines the access specifier oftne
members ofthe base class inside the derived class. The access specifier of a base clas
member in the derived class depends on the access specifier provided while defining
derived class. Depending on the access specifiers public, protected base
or private, a
class can be inherited publicly, protectedly or privately
respectively.
Publicly Inherited Base Class:
When the access specifier of the base the
class in the derived class definition is public,
puoin
base class is publicly inherited. The access emains
specifier
the same in the derived class. This of the base class me
implies, the public members of the base class
thepublic members of the derived class and protected
rema
e
the protected members of the derived members of the base cled
class.
Vo-
nce in C++.
inhentance C++, Pointers to Objects, Input-Output
and Manipulators in Ct+ 111
slrking
with
Base Class
Private Members
Protected Memberss
Public Member
Derived Class
Private Members
Protected Members
Public Member
member functions, friend classes and the friend functions of the derived class.
Program to demonstrate
-
Publicly Inherited Base ClasS:
#inciudeciostream. h>
#inciudecconio.h»
ciass basse
int b_pri;
protected:
int bpro;
pubiic:
int b_pub;
void setO
b_pri=1;
b_pro=2;
b_pub=3;
private:
protected:
public
void shoaO
coute<"\nPrivate member:"<cb_pri;
Cout&"\nProtected member: "<<bpro;
Cout"\nPublic member: "<<b_pub;
vid nainO
112
clrscrO;
are accesSible in derivved class"
derived d; class
of base
************************t"
members
d.set); Following Data
COut<<"\n***********************
Cout<"\n
d.show); "<cd.b_pri;
accessible outside":
member:
cout<"\nPrivate member: "<<d.bpro; are
/7
cout«"\nProtected members of base class
cout<<"\n\nFollowing data
"<<d.b_pub;
cout««"\nPublic member in main:
getch():
class
Output: are accessible in derived
members of base class
Following Data
2
Protected member:
Public member: 3
accessible outside
Following data members of base class are
Protected Members
Public Members
Derived Class
Private Members
Protected Members
Public Members
iend
thebase class can be accessed by the member functions, the friend classes an
functions of the derived class.
with
aritance in C
inheritance Ct*, Pointers to Objects, Input-Output
and Manipulators in C++ 113
Hwis
Frogramto
demo
demonstrate Protectedly Inherited Base class:
gincudesiostream. h>
inc1vdesconio. h>
base
class
int bpri;
protected:
int bpro;
public:
int bpub;
void set(
b_pri-1;
bpro-2;:
bpub-3;
private:
protected:
public:
void show)
base::set();
// cout<<"\nPrivate member: "<<b-pri;
cout"\nProtected member: "<<b_pro;
cout<<"\nPublic member: "<<b_pub;
void rainO0
cirserO:
derived d;
I/d.setO;
in derived class";
cout«<"\n Fol1owing Data members of base class are accessible
coute"\n******* ********************** *****************"
4.shonO:
/cout««"\nPrivate member: "<<d.b-pri;
i cout<«"\nProtected member: "<<d.b-pro;
outside";
E n\nFollowing data members of base class are accessible
E n*******ttttt*t***t*tt************** ****** ****** *"
cout&"\nPublic member in main: "<<d.bpub;
9etch
Vipul'S OOJe u ramming
rTOgrammin
WihC
114
1n derived class
Output: are accessible
members of base class
|FOTlowing Data
2
Protected member:
3
Public member:
are accessible outside
Following data members of base class
Protected Members
Derived Class
Private Members
Public Members
Protected Members
class base
int bpri:
protected:
int b_pro;
public:
int b_pub;
void set()
bpri-1;
bpro-2;
b_pub=3;
nheritanc
heritance in C++, Pointers to Objects, Input-Output and Manipulators
l
115
WIth in Ct
twAinN
derived:private base
/class
private
protected
pub7icshowC)
void
base::set);
cout<e"\ rivate member: "<<b_pri;
ute"\nProtected member: "<<b_pro;
cout<"\nPublic member: "<<b_pub;
main(0
oid
clrscr);
derived d;
//d.set);
lte"\n Following Data members of base class are accessible in derived class"
cout"\n************s
d.show);
cout««"\nPrivate member:"<<d.bupri;
/ cout««"\nProtected member: "<<d.b_pro;
/
cout"\n\nFollowing data members of base class are accessible outside";
coute\n**
/ cout<<"\nPublic member in main: "<<d.b-pub;
getch):
Output:
Following Data members of base class are accessible in derived class
Protected member: 2
Ablic member: 3
class base
int bpri
protected:
int b_pro;
public:
int bpub;
void set)
b_pri=1;
b_pro=2;
b_pub-3;
// cout<"\nPrivate member:"<<b_pri;
cout«"\nProtected member:"<<b_pro;
coute<"\nPublic member: "<<b-pub;
void main()
clrscrO
derived d;
d.set)
cout<<"\n Followi ng Data members of base class are
accessible
cout<<"\n************************************************"
in derived class
d.showO;
// cout«<"\nPrivate member: "<<d.b_pri;
// cout««"\nProtected member: "<<d.b-pro;
cout<<"\n\nFoll owi ng data
members of base class are
coutk"\n*********************************** accessible outsi de";
*********s* * **"
cout<"\nPublic member in main:"<<d.bupub;
getch ();
117
aitance în C*, Pointers to Objects, Input-Output and Manipulators in C++
Inhe
WvNNh
class base
int b_pri;
protected:
int b_pro0
public:
int bpub;
private:
char name[20];
protected:
float f;
publi
void mainO
clrscrO:
base
b;
derived
d;
11S
"<<sizeof(b):
Base class: "<<sizeof(d);
cout««"\n Size of Derived cass:
cout<<"\n Size of
getch0
Output:
6
Size of Base ciass:
Size of Derived class: 30
Single Inheritance a single base class, it is
referred to
+
as sin
inherits from
When a derived class members
In single inheritance, the derived clas inherits all the of all itsbas
inheritance. protected members of the base clasc
directly access the public and
class and can
Program to demonstrate Single Inheritance:
#inciude<iostream.h>
#include<conio.h>
class person
cout<<"\nEnter name:";
cin>>nane;
cout«"\nEnter age:";
cin>>age;
void showdata ()
cout<<"\nName: "<<name;
cout<«"\nAge: "<<age;
int salary;
public:
void getsal )
cout<"\nEnter salary:";
cin>>salary;
void showsal ()
cout«<"\nSalary: "<<salary;
void main()
C++, Pointers to Objects, Input-Output 119
nheritance in Ct+, Po
lnheritance and Manipulators in C++
Working with
cirscrO;
emp1oyee e;
Enter employees' data";
cout "\nt*** ****** ******
cout<<"\n******** ***** *"
e.getdata0;
e.getsal(O:
coute"\n\nEmployees' Info."
cout"\n******* *****"
showdata();
itsb
e.showsa7);
e.
getch);
Output:
emp 1oyees data
Enter ****** *****
*******
Enter name:
Sanjeela
age: 31
Enter 20000
Enter salary:
Employees Info.
*************
Nane: Sanjeela
Age: 31
Salary: 2000
Example 1:
Write a program to implement single inheritance from following figure. Accept and
display products flavors only with sweet.
Class Product
Data members: product_id, Name
Class Edible
Data members: Weight, price, flavor
#include<iostream.h>
#includecconio.h>
#include<string.h>
class Product
int product_id;
char Name
[801
public:
void getdata ()
Vipul'sM Object OrlentedProgramming
Programmi.
120 with
cs,
name: "i
Cout<"\nEnter product id and product
cin>>product-id>>Name;
}
void showdata ()
"<<Name;
cout«<"\nProduct Id: "<<product-id«<"\tProduct Name:
Product::getdata();
cout«<"\nEnter weight, price and flavor: ";
cin>>weight>>price>>flavor;
void showdata ()
Product: : showdata();
cout<"\nWeight: "<<weight«<"\tPrice: "<<price«<"\tFlavor: "<<flavor;
char getflavor ()
return flavor;
void main()
{
Edible e[5];
int i;
char f[80];
forCi=0;i<5;i++)
elil.getdata();
forCi-0;i<5;i++)
strcpy(f, e[i].getflavor());
if(stremp(f, "sweet")==0))
e[i].showdata();
Inherltance
sorltance in
In C++, Polnters to Objects, Input-Output
wilth and Manlpulators In C++ 12
workling
Multiple Inheritance:
14 n A derived class inherits from more than one base class simultaneously, it is
When
inh
muitiple inheritance. In multiple inheritance, the derived class inherits a
erred to as multiple
eferhers
member of all its base class and can directly access the public and protectec
the
members the base classes.
of
am
to demonstrate Multiple
Program to Inheritance:
gincTudec10Stream. h>
pinclude<conio. h>
person
class
name [30];
char
int age;
pub1ic:
void getdata()
void showdata()
cout«"\nName: "<<name;
cout&«"\nAge: "<<age;
Class employee
int salary;
publi
void getsal()
cout«"\nEnter salary:";
cin>>salary;
void showsal
()
cout"nSalary: "<<salary;
class
fulltime:public person,
public employee
void main(O
clrscr)
fulltine
cOut"nfEnter
employees' data";
Vipul'sM Object Oriented ogramming
122 with
ci
f.getdata():
f.getsal (O:
cout<<"\n\nEmp1oyees' Info. ";
f. showdata();
f.showsa1 ();
getch
Output:
Enter employees' data
Emp1oyees' Info.
************** * * ****
Name: Sanjeela
Age: 31
Salary: 2000
Ambiguity Resolution in Multiple Inheritance:
In multiple inheritance, an ambiguity may arise when two or more
base classes have
a member with the same name. In order to resolve such
ambiguities, the name of the
member is qualified with the name of the base class by using the
scope resolution
operator.
Program to demonstrate Ambiguity in Multiple Inheritance:
#include<iostream.h>
#includecconio.h>
Class person
cout««"\nEnter name:";
cin>>name;
cout<"\nEnter age:";
cin>>age;
}
void showdata()
cout«"\nName: "<<name;
cout<<"\nAge:"<<age;
serltance in Ct+, Pointers to Objects, Input-Output
Workingwith and Manipulators in C++ 123
emp oyee
c]ass
salarY
int
public: ()
void getda ta
cOut"\nEnter salary:";
cin>>salary;
void
showsal ()
"<<sal1lary;
cout <«"\nSalary:
mainCO
void
clrscr;
fulltime f:
coutee"\n Enter employees' data";
assesh ost"\n*************************"
amecd / f.getdata(); Ambiguity
cOut<<"\n\nEmployees' Info.";
resoli COut&<"\n*****:
************ ****"
getch);
class person
Char name
[30];
int age;
public:
void getdata()
class employee
int salary;
public:
void getdata ()
void showsal ()
cout«"\nSalary:"<«salary:
9
person, public employee
class fulltime:public
void main)
clrscrO
fulltimef:
cout<<"\n Enter employees' data";
cout<<"\n******************t#***t*"
f.person: :getdata(O: //Ambiguity resolved
f.employee: :getdata();
cout«"\n \nEmployees' Info. ";
cout<<"\n********************";
f. showdata):
0;
f.showsal
getch O;
|Output:t
Enter employees data
* ****t****tt*
*****ttt
demons
Multilevel Inheritance:
Program todemonstrate
tream. h>
pincludecios
includecconio. h>
person
class
name[30);
char
age;
int
pub1ic:
()
void getdata
out«<"\nEnter name: ";
cin>>name;
cout<<"\nEnter age: "
cin>>age;
void showdata ()
cout<<"\nName:"<<name;;
cout«<"\nAge: "<<age;
person
class employee: public
int salary;
public:
void getsal()
void showsal)
cout««"\nSalary: "<<salary
char sub[30]
public:
void getsub()
name:
cout&"\nEnter subject
cin>>sub;
"
void showsub)
void main()
Vipul'sN Object Oriented Programming
wtt
126
clrscr);
fulltime f; employees data";
cout<<"\n Enter ********** * * *s*****";
Cout<<"\n******
f.getdata):
f.getsal0:
f.getsub);
cout<"\n\nEmployees' Info. ";
Cout<<"\n********************"
f. showdata ();
f. showsal);
f. showsub);
getch ();
Output:
Enter emp1oyees' data
************************
Enter name: Sanjeela
Enter age: 31
Enter salary: 2000
Enter subject name: 0OPS
Employees' Info.
****** **************
Name: Sanjeela
Age: 31
Salary: 2000
Subject to be taken: 00PS
Example 2:
figure. Acce=
Write a program to implement multilevel inheritance from following
and display data for one student.
Class Student
Data members: Roll_no, Name
Class Test
Data members: marks 1, marks 2
due
Class Result
Data members: total
127
Input-Output and Manipulators in C++
Inheritance in C+, Pointers to Objects,
tance
with
Horking
1udeciostream.
nc1ude<conio.ha
Student
class
rollno;
int namel50];
har
pub7ic getdata()
void
"Enter student RolT no and name:";
Coute"
cim>rollno>>name;
showdata ()
void
class Test:public
Student
marks1, marks2;
int
public:
void getdata()
Student::getdata()
Cout«"Enter Marks1 and Marks2: ";
cin>>markslb>marks2;:
Accep
void showdata ()
Student::showdata();
cout«<"\nMarks1:"<<marks1<<"\tMarks2: "<<marks2;
int getMarks1()
return marks1;
int getMarks20
return marks2;
128
Result:public Test
class
int total;
public:
void getdata ()
Test::getdata();
void showdata ()
void main()
clrscr)
Result r 5tu7iidue 1
r.getdata();
r.showdata();
getch)
Output:
name: 101 Sanjeela
Enter student Rol1 no and 78 88
Enter Marks1 and Marks2:
Ro11 No: 101 Name: Sanjeela
Marks1: 78 Marks2: 88
Total Marks: 166
3.1.5 Hierarchical Inheritance:
one class=
Hierarchical inheritance is a type of inheritance in which more than
class provic
derived from a single base class. In hierarchical inheritance, a base
members that are common to all of its derived classes.
of
In hierarchical inheritance, each of the derived class inherits, all the members
base class. In addition, all the derived classes can directly access the publica
protected members of the base class. However, one derived class cannot access
members of another derived class.
Program to demonstrate HierarchicalInheritance:
#includeciostream.h>
#include<conio.h»
class emp1oyee
age;
int
public:
void
getdata ()
cout<<"\nEnter name: ".
"
cin>>name;
cout<<"En ter age: ";
cin>>age
showdata ()
void
cout<<"\nName:<<name;
cout<<"\nAge: <<age;
int salary
public:
void getsal()
cout«<"Enter salary: ";
cin>>salary;
void showsa1 ()
cout"\nSalary: "<<salary;
int hrs_worked;
int wages perhr;
public:
void calsal ()
void showcalsal ()
"<<hrs_worked*wages_perhr;
U"nTotal Salary:
void mainC
clrscr)
fulltime
Cout f
nEnter Fu11 Ti me employees data";
n*************** ** ***************
130
f.getdata();
Employees' data";
f.getsa1(); ***********d***************".
coute<"\nEnter Contract
cout<<"\n**
contract C;
c.getdata ();
c.calsa1(); Employees' Info. "
cOut<<"\n*******d**ddd****dd*******",
cOut<<"\nFul1 Time
f. showdata ();
showsal();
f.cout<<"\n\nContract Employees' Info.";
****"
cout<<"\n**********s
c.showdata);
C.showcalsal );
getch ;
Output:t
Time employees data
Enter Full
Enter name: Sanjeela
Enter age: 31
Enter salary: 20000
|
Name: Sanjeela
Age: 31
Salary: 20000
Name: Sanju
Age: 29
Total Salary: 12000
3.1.6 Virtual Base Class:
An abstract class is a class that contains
at least one pure virtual function. In tne
declaration, if the declaration of a virtual
(0) to the function declaration member function is done by appending
then the function is pure virtual
function.
inheritan
eance in C+, Pointers to Objects, Input-Output and Manipulators 131
in C+*
#Ykingwln
example,
For
base
class
pubiic
void dis
display ) 0:
=
void
virtua
abstract class cannot be used as a parameter type, a function return type, or the
it conversion type ine most important thing is that one cannot declare the object
eNp
hctract class. However, declaring pointers and references to an stract class is
an
passible.
A virtual member runctions can be inherited, a class derived from an abstract
can
dass
also be abstract unless overriding of each pure virtual function in the derived
can also
done.
dassis
For example,
Frogramto demonstrate Abstract Base Class:
#includeciostream. h>
#include<conio. h>
Using abstract methods and classes.
class Figure
public:
dim1;
double
double dim2;
Figure (double a, double b)
dinl a;
din2 b;
public:
utnInside
return dim1
Area for Rectangle:
*
dim2;
class
Triangle:public
Figure
132
public:
Figure(a,b)
TriangleCdouble a, double b):
void main)
ClrscrO:
Rectang1e r(9, 5);
Triangle t(10, 8);
cout<< r.area();
cout« t.area);
getch )
Output:
Inside Area for Rectangle:45
Inside Area for Triangle:440
3.1.7 Constructor and Destructor in Inheritance:
are
The constructors of the base classes and constructors of the derived class
automatically executed when an object of the derived class is created. The constructors
of the base classes are executed first and then the constructor of the derived class is
executed. In mulitple inheritance, the constructors of base classes are executed in tne
same order in which the base classes are specified in derived class(i.e. from left to right,
Similarly, the destructors are executed in reverse order, i.e. derived class constructor
is executed first and then constructors of the base classes are executed (from right to to
left).
If the constructors of the base classes have no parameters, then the syntax to c reate
relationship between derived class and base classes is very simple.
For example,
Program to demonstrate Order of calling Constructor and Destructor in ce:
#include <iostream> inheritan
using namespace std;
pubTic:
parent (
//constructor
"Parent class Constructor called\n";
parentO //destructor
cout << "Parent class Destructor called\n";
Tienf
public:
child) //constructor
cout << "Child class Constructor ca11ed\n";
int main()
synta
inhemi
co
constructors and destructors because of inheritance
child c;
return 0;
Vipul's Object Oriented Programm
Ogramming
134 with
C
Output:
Parent class Constructor called
Child class Constructor called
Child class Destructor called
Parent class Destructor called
3.18 Containership:
has an object of
Composition is also referred to as nesting, in which class
a of another
or aggregation or containershi.
class as its members. Composition or containment
between clase ke
inheritance, enables the implementing of a logical relationship
access only to the
nesting, the class (enclosing class) that contains an object has clae
members of that class. The private and the protected members of the contained
clase
not accessible to the enclosing class. However, in inheritance, the derived Can
access the protected members of the base class.
class colony
void show0
cout<"\n, "<<address;
class room
cout«"\nAddress\n";
Inheritane
heritance in C+*,Polnters to Objects, Input-Output
NvAW th and Manipulators In C 135
cout"\n-.
cou n"<eroomno
";
coute"\n «<"7 "<<bldgno;
cl.show):
mainC)
oid
ndthe clrscr);
roam r
get);
showC):
pudis r.
etch)
Output:
Enter room number: 15
Enter building number: 98
ater address: Wadala(E), Mumbai.
Address
15/ 99,
Wada (E), Mumbai.
la
between Composition and Inheritance:
Difference
Composition Inheritance
The object of one class is used as al The object of one class inherits the
member in another class. property of another class.
Does not support the concept of Supports the concept of reusability.
reusability.
Does not provide additional features Provides additional features to an
to existing class. existing class.
- KIND -
Represents 'HAS - A' relationship. Represents 'IS - A OF
relationship.
Example: Example:
House Room
Room
Dining Reading
RoomRoom L Hall
Ugr
Vipul's' Object anming with
Cs
FUNCTIONS:
136 VIRTUAL
OBJECTS AND
POINTERS TO
3.2 pointers to objects,.
3.2.1 Pointer to
Objects: variables, you can have
pointers to other types of
to an object, use the ar
Just as you have of a class given
a pointer (
members
When accessing operator.
operator instead of the dot
For example,
Pointer to Object:
Program to demonstrate
#include<iostream>
namespace std;
using
//Pointers to objects
class student
char name [20];
int age;
public:
(O
void get
void show)
cout"\nName: "<<name;
cout"\nAge:cage;
student S; lessot9
student *ptr;
S.getO;
ptr=&s;
ptr->show ();
return 0;
Output:
Enter name: Sanjeela
Enter age: 33
Name: Sanjeela
Age: 33
3.2.2 The This Pointer:
The "this"pointer is a special pointer class
currently calling the member function that contains the address of an object a callsScal15
of the class. Whenever an
object of the class
clas>
tance in C++,
Inheritance C+*, Po
Pointers to Objects, Input-Output and Manipulators
in C++ 137
with
Working **
on-static member function, the address of the object (this pointer) is passed as
implici argument (or as a hidden argument) to it and is available as a local variable
anyiit
an within its
w
body.
The ata
members of the caling object can be accessed within the member functions
directly using their names or indirectly using the'operator with this pointer. In
eitherdired
he this pointer can be used to return the object pointed to by it, to the calling
ition, the
program.
int n;
public:
abc)
n-0;
abc(int n)
this->n n
void showO
Cout<<n
if(n>aa.n)
return *this;
else
return aa;
void mainO
clrscr);
abc al(10),a2 (20),a3;
a3=a1.large(a2);
Cout«cendl«<"Object 1 data: ";
al.show():
cout<cendl<<"0bject 2 data: ";
a2.showC):
coute"\nLargest object data: ";
a3.show):
getch )
fa
Vipul'sM Object Oriented Programming maaahio
withc
138
Output: lhata
Object 1 data: 10
nles
heried
Object 2 data: 20 Work
Largest object data: 20 a parameter of the
same name as a mer
Note that our constructor is takingparameter and 'this > n' refers to the
Avtual
tho mbe
member class
variable. In this case, 'n' refers to the
variable.
return the object it was Class15
workino.with ASe
ed
Occasionally it can be useful to have a function was passed
object that implicitly
Returning *this' will return a reference to the the
function aplersel
3.2.3 What is Binding in C++? (arthlenlisof
to be executed resnn
Binding refers to the linking of a procedure call to the code in onseEalayingd
with a procedure that2
to the call. Dynamic binding means that the code associated given
apler
is not known until the time of the call at run-time. It is associated with polymorphic
and inheritance. A function call associated with a polymorphic reference depends onthe
kervedd
dynamic type of that reference.
At run-time, the code matching the object under current reference will be called. sebptry
3.2.3.1 Virtual Functions:
Virtual functions in C++ support run-time polymorphism. A virtual function is a Show
member function that is declared inside the base class and its functionality can be t=&cd,
overridden in the derived classes. When the base class containing virtual function is otr=Show
inherited, the derived classes may implement their own versions of that function.
Thefavirtu
entire function of the base class can be replaced by a set of new implementation in the lfa
virtua
derived class. This implies that the base class provides a common interface and this
CEember fune
interface can be implemented in different ways in different derived classes. A member
function can be made virtual by prefixing its declaration with the keyword virtual in the
base class. For example, TEhanisim
i
class Base
Eamto
public ludeciost
cludeecoi
virtual void Show()
{ cout <« "Show of base class"; assbase
public:
void Show()
cout <« "Show
terive
of derived class";
ritance in C+, Point
nheritan binters to Objects, Input-Output
and Manipulators in
with Ct+
Werking 139
in.when a derived class that has inherited
ada a virtual function itself
n
base
for
class to another derived class, the virtual function can is used as
still be overridden. This
ainplhes at a virtual fun
function always remains
virtual irrespective of the number
of times
inherited
is Working of a Virtu; Function:
it323.2
..nl function must be accessed using a pointer of
base class type and not of
rived Alass type. However, if the function is not
declared virtual and the pointer of
made to point to the derived class, the function
base of the base class is always
That is, the complier selects a function on the basis of the
xeC type of pointer
instead its Contents. However, if the function is declared virtual in the base class, the
Complierselects which ich version of the function is to be executed depending upon
the
ts of the point
pointer. Moreover, this decision is made at the run-time, thereby,
ovingemploy dynamic binding. Hence, declaring a member function virtual informs the
complier that the ffunction call is resolved at run-time. For example,
endt
Base b; // object of Base class
derived d; l/object of Derived class
Base bptr; //Pointer of type base
bptr=&b; //Pointing to base class
//Show() of base class
ybptrshow0;
//Pointing to derived class
nbptr= ed;
tion
bptr= Show(); //Show() of derived class
in Ifa
on virtual function is not redefined in the derived class, a call to that function uses
the function implementation defined in the base class. Moreover, like a non-virtual
m-member
ne
function, a virtual member function can be accessed directly in the derived class
alusing the scope resolution operator (:). However, in this case, the virtual function
mechanism is suppressed and the base class implementation of the function is classed.
class base
public:
alvirtualvoid display()
eque
coutee"nDisplay of base class called"
void main)
clrscr):
base *b;
derived d;
b=&d;
b->display);
getch):
Output: called
Display of derived class Function:
3.2.3.3 Rules for Virtual
functions must be members of some class.
The virtual
members.
They cannot be static
pointers.
They are accessed by using object
a friend of another class.
A virtual function can be even though it may notbe used.
class must be defined,
A virtual function in a base in the derived classes must
its redefined versions
The base class virtual function and
same prototype. However, if the prototype differs, the complier considers
have the
functionns.
these functions as overloaded
of a base cannot be made virtual, however, the destructors can be
The constructors
made virtual.
tyype of the derived object, but we cannot use a
A base pointer can point to any
pointer to a derived class to access an object of the base type.
incrementing or decrementing the pointer of base type, it will always point to
tne
On
of the
next or the previous object respectively of its base class type, irrespective
contents of the pointer.
3.2.3.4 Pure Virtual Function and Abstract Class:
If a derived class does not redefine a virtual function, the base class implementato
ngful
of the virtual function is invoked. However, in some cases, either no meanin
definition of the virtual function exists in the base class or each derived class 1S rE
to define its own version of the virtual function. To handle such cases, C++ provu vides
pure virtual functions.
A virtual function that has no definition pure
within the base class is known as a"ot
virtual function. A virtual function can be
made pure by appending thepure pu speci
nction
nction
'=0' to its declaration in the base class.
The syntax for declaring a pure virtua
is
virtual return_type functionName
(argumentlist) = 0;
with ance in C++, Pointers to Objects, Input-Output
Working and Manipulators
in C++
example: 141
For
student
class
4d Show(O = 0; //pure
virtua virtual function
class base
pub7ic:
irtual void show)=0; // pure virtual1 function
public:
void showO
void main()
clrscrO;
child1 c1;
cl.show);
child2 c2;
c2.show):
getch)
142 P** Jett onened ri8rdmmine
win
Output:
Show method of child1called
Show method of child2 called
Example:
and 'rectangle from clase
Create class Shape. Derive two classes 'triangle
rectangle to accept dimensipe
Write appropriate functions in class triangle and
for calculating area. Here make area) function virtual w
triangle and rectangle
and rectangle interactivel.is
common for all and which will calculate area of triangle
#include<iostream.h>
#include<conio.h>
class Shape
public:
virtual int Area()=0;
void showdata ()
int Area()
return (base*height)/2;
void showdata ()
Inheritanr in Ct+, Pointers to Objects,
o
Input-Output
with and Manipulators
working in C++
143
\nWidth: "width«<"\tHei
cout<"| "<<height
Area(
int
n (width*height);
y.
mainC
void
clrscrO;
int a t;
Triangle
t.getdata();
Rectangler;
r.getdata(;
showdata(0;
t.at.Area() :
COut<"\nArea of triangle: "<<a;
r.showdata);
a=r.Area();
cout&"\nArea of rectangle: "<<a;
getch);
Output:
Enter base and height of triangle: 12 6
Enter width and height of rectangle: 12 13
Base: 12 Height: 6
Area of triangle: 36
idth: 12 Height: 13
Area of rectangle: 156
3.2.3.5
Object Slicing:
When a derived class object is passed by value as a base class object, as in foo(Base
derived_obj),
the base class copy constructor is called. So, the specific behaviours of a
EIVed class object are sliced off. We're left with a base class object. In other words, if
pcast(Upcasting and Down Casting) to an object instead of a pointer or reference,
is sliced. As a result, all that remains is the sub object that
corresponds to the
Aect
destination
typ of our cast as shown in the example beloW:
Pr
Ogram to demonstrate object
includeciostream.h> slicin8
#includecconio.h>
Class
8
gramimin,
Hth
144
public:
int i
B
class D : public
public:
int ji
int main)
B B1;
DD B1
B1 = D1; //only i is copied to
Function:
3.2.3.6 Some Facts about Virtual objects of class. virtual mechani
Virtual functions can be called explicitly using
works only in case of pointers to object.
A pure virtual function can have body
but in no way we can use this body,
3.2.3.7 Virtual Destructor:
its behaviour is determined
A virtual method has no direct implementation and
the method with the same signature that
is on the lowest inheritance level of t
object is destroved.
instantiated object. A destructor is automatically called when the
virtual destructor in C++ is used primarily to prevent resource leaks
by performine
clean-up of the object.
The following steps explain how to use virtual destructors:
.Determine when to use a virtual destructor. A destructor for a class should be virtual
when an object of a derived class will be destroyed by invoking the base clas
destructor. The destructor must be virtual when you delete a pointer to an objectand
it is possible that it points to a derived class.
The difference between a destructor and other methods is, in both cases, the metho
of the derived class is invoked if it is implemented. However, the base clas
destructors is subsequently called whereas this does not happen with other methous
For example,
Program to demonstrate Virtual Destructor:
#include<iostream.h>
#include<conio.h>
class base
public:
base()
cout<endl«<"Base class
constructor called";
Inheritance in C++,
Ct+, FPointers to Objects, Input-Output and
Norking with
Manipulators in C++ V"V"V" 145
virtualbase()
c1ass
derived:public base
public
derived()
derived()
nte ain()
void
DyClrscr();
derived *d= new derived ();
delete d;
getch():
hr
Output:
class constructor cal1ed
Base
Derived class constructor called
Destructor of derived class called
Destructor of base class called
Observe the use of the virtual keyword in the above program (virtual base () ). If -
the destructor of the base class were not declared as virtual, the destructor of the
derived class would not get called.
Implement at least an empty body for a virtual destructor, since a pure virtual
function cannot be declared.
output stream
Output
device
ios_base
ios
istream Ostream
(input) (Output)
istream_withassign ostream_withassign
(cin) lostream (cout, cerr, clog)
iostream_withassign
,
Fig
.ritance in C#+
Inheritance C++, Pointers to Objects, Input-Output
and Manipulators in C++ 147
werking with
so it can
be used.
he Ostream class is the prinmary class used when dealing with output streams. With
Th
output streams, the insertion operator (<) is used to put values in the stream
uses them.)
(e.g. monitor
The iostream class can handle both input and output, allowing bidirectional 1/O.
Finally, there are a bunch of classes that end in "_withassign". These stream classes
are derived from 1stream, ostream, and iostream (respectively) with an assignment
anerator defined, allowing you to assign one stream to another. In most cases, you won't
opera
bedealing with these classes directly.
Standard streams in C++:
A standard stream is a pre-connected stream provided to a computer program by its
IS. environment. C++ comes with four predefined standard stream objects that have
already been set up for your use. The first two, you have seen before:
) cin: an istream_withassign class tied to the standard input (typically the
keyboard)
(2) cout: an ostream_withassign class tied to the standard output (typically the
monitor)
(3) cer an ostream_withassign class tied to the standard error (typically the
monitor), providing unbuffered output
(4) clog: an ostream_withassign class tied to the standard error (typically the
monitor), providing buffered output
Unbuffered output is typically handled immediately, whereas buffered output is
typically stored and written out as a block. Because clog isn't used very often, it is often
omitted from the list of standard streams.
Input with istream:
When reading strings, one common problem with the extraction operator is how to
Keep the input from overflowing your butfer. Given the following example:
char s[10]; cin>>s;
What happens if the user enters 18 characters? The buffer overflows, and bad stuff
happens.
char ch;
while (cin >> ch)
cout << ch;
char ch;
while (cin.get(ch) )
cout << ch;
char s[11];
// Read up to 10 characters
cin.get1ine (s, 11);
neade
inneritancei
ance in C++, Pointers to Objects, Input-Output and Manipulators in 149
Witn C++
x, Working
and cout << s << end1;
o 10 more characterss
Read up to
cin.getline(s,end1;11);
<<
cout < s
ne nore useful istream functions:
ceam tea Few
we are a few more useful
discards the first
input functions that you might want to make use of:
urt ignore( character in the stream.
ignore(int discards the first n characters.
n):
xtracion
and peek0: allows you to read a character from the stream without removing it from the
De Pstream.
11nget0:
ui ge
returns the last character read back into the stream so it can be read again
by the next call.
nutback(char c) allows you to put a character of your choice back into the stream to
put
be read by the next call.
3.3.2 Unformatted Input/Output .
C cin.get();
Program to demonstrate get():
#include<iostream>
void main ()
char ci
cout <"Enter a character:";
C cin. get);
cout <<"The character c = "<< C << endl;
Output:
Enter a character :A
The character c = A
getline
The function is object .for reading complete line, for instanc-
xactly le Cin.getline(). used with istream
Output:
Enter a name: Sanjeela
name: Sanjeela
You have entered the
read) and writel): stream
functions read() is a member function of istream and is used with input ams
The hence it i
is a member function of ostream and
such as cin.read(). The function write()
The function write() does output of a
used with output streams such as cout.write().
memory without any formatting
number of bytes from the character array in the some bytes without anv
read() does input into the memory
Similary the function
() take two arguments as illustrated
formatting. Both the functions read() and write
below.
char name[15);
cin.read (name,15);
cout.write(name, 15);
|Program to demonstrate write() and read():
#include <iostream, h>
Void main)
// bytes/characters
char name [15];
cout«"Enter a name: "
cin.read(name ,15): // asked to read 15 bytes/char
cout.write( name, 15) <cendl; /1 asked to write 15
//bytes from Name
inheritance
eritance in C++, Pointers to Objects, Input-Output
Working with and Manipulators in Ct+
Output:
Sanjeela Sagar
ch A
ABCDE
name: Rakesh
Enter a
Rakesh
3.3.3 Formatted Input /Output Operations:
re are two ways to change the formatting options:
There
flags, and manipulators. You
can hink of flags
as boolean variables that
can be turned on and off. Manipulators are
objectsplaced in a stream that affect he way things are input and output.
To Switch a flag on, use the setf0 function,
To with the appropriate flag as a parameter.
For example, by default, C++ does not print a + sign in front of positive numbers.
Howevever, by using the ios::showpos flag, we can change
:showpos); this behavior:
cout.setf(ios: // turn on the ios::showpos flag.
cout << 10 << end1;
This results în The following output:
+10
It 1S possible to turn on multiple ios flags at once using the OR C1) operator:
cout.setf(ios:: showpos ios::uppercase): /7 turn on thne
1/ios::showpos and ios::uppercase flag
cout << 10 << end1;
To turn a flag off, use the unsetf) function:
cout.setf(10s: :showpos); /7 turn on the
1/ios:: showpos flag
cout << 10 << end1;
cout.unsetf(ios::showpos); I/ turn off the
I/ ios::showpos flag
cout << 11 << end1;
This results in the following output:
+10
11
Many flags belong to groups, called format groups. A format group is a group of
flags that perform similar (sometimes mutually exclusive) formatting options. For
example, a format group named "basefield" contains the flags "oct", "dec", and "hex",
which controls the base of integral values. By default, the "dec" flag is set.
Consequently, if we do this:
cout.setf(ios: :hex) ; 1/ try to turn on hex output
cout «< 15 <« endl
We
get the following output:
15
Itdidn't work! The reason why is because setf() only turns flags on- it isn't smart
enough to turn mutually exclusive flags off. Consequently, when we turned ios:hex on,
10S::dec was still on, and ios::dec apparently takes precedence. There are two ways to get
around this problem.
st, we can turn off ios: :dec so that only ios::hex is set:
unsetf Cios: dec); // turn offdecimal output
Setf(ios: :hex) ;
// turn on hexadecimal output
152
Y Vipul'sM Object Oriented Programming
14
25
Useful formatters:
Here is a list of some of the more
Flags live in the ios class, useful flags, manipulators, and
manipulators lives in the std namespace,member functions
functions live in the ostream class. and the member
Manipulator
Meaningg
showpos Prefixes positive numbers
with a +
no showpos Doesn't prefix positive numbers
Example: with a +
cout <<15 << end1;
cout.setf(ios::showpos);
cout «< 15 <« end1;
cout << noshowpos <<
15 << end1;
cout << showpos <«
15 << end1;
Result:
15
+15 1
15
+15 9
Manipulator
uppercase Meaning
Uses upper case
no uppercase letters
Uses lower case letters
inheritance
in C++, Pointers to objects, Input-output and Manipulators
1workingwith
in C++ Y"Y" 153
. Example:
678.9 <
123456
« :upperca
end1;
case);
co etf(ios:
12345678.9 < end1;
ana Co << 2345678.9<< endl;
cout noupoercase
cout uppercase << 123
12345678.9 << end1:
out
Result:
.23457e+007
1.23457E+007
1.23457e+007
1.23457E+007
Flag Meaninng
Group
Sis basefield dec Prints values in decimal (default)
basefield hex Prints values in hexadecimal
basefield Oct Prints values in octal
Manipulator Meaning
dec Prints values in decimal
embExample:
Cout 15 << end1;
cOut.setf(ios::decC, ios::basefiel1d);
Cout 15 << end1;
cOut.setf(ios::oct, ios::basefield);
cout < 15 << endl;
cout.setf(ios::hex, ios:: basefield);
cout < 15 << end1;
cout << dec << 15 << end1
cout << oct << 15 << endl1;
cout< hex << 15 << end1;
Result:
5
Der
1.23450e-+004 1.23450e-001
1.234500e+004 1.234500e-001
Width, fill characters, and justification:
Typically when you print numbers, the numbers are printed without any regard to
the SDace around them. However, it is
possible to left or right justify the printing of
numbers. In order to do this, we have to first
define a field width, which defines the
number of output spaces a value will have. If
the actual number printed is smaller than
the field width, it will be left or right justified (as specified).
If the actual number is
largerthan the field width, it will not be
truncated --it will overflow the field.
Group Flag Meaning
2djustfield internal|Left-justifies the sign of the number, and
right-justifies the value
adjustfield
left |Left-justifies the sign and value
adjustfieldright
Right-justifies the sign and value (default)
33.4 Manipulators:
Manipulator
Meaning
nternal
Left-justifies the sign of the number, and right-justifies the value
eft
ight Left-justifies the sign and value
|Right-justifies the sign and value
156 vipul'sTM Object Oriented Prograrmming
witt c,
setfill(char) Sets the parameter as the fill fined
character (defined in
in iomani
iomanip.)
setw(int) Sets the field width for input and output to the parameta
in ionmanip.h) defined