You are on page 1of 54

Inheritance and Polymorphism

Inheritance and its types, protected class members , overriding


and dominating inherited members
Virtual Base Class, Abstract class, pointers, pointers to objects,
this pointer, Virtual functions and polymorphism, Virtual
functions, Pure Virtual functions
Inheritance is one of the most useful and essential characteristics of
object-oriented programming. The existing classes are the main
components of inheritance.
The new classes are created from existing ones. The properties of the
existing classes are simply extended to the new classes. The new classes
created by using such a method are known as derived classes, and the
existing classes are known as base classes.
 The relationship between the base and derived classes is known as kind
of relationship. The programmer can define new member variables and
functions in the derived class. The base class remains unchanged.
The object of the derived class can access members of the base as well as
derived classes. On the other hand, the object of the base class cannot
access members of the derived classes. The base class does not know
about their subclasses.
REUSABILITY

Reusability means the reuse of properties of the base class in the


derived classes. Reusability permits the reuse of members of the
previous class. We can add extra features in the existing class.
This is possible by creating a new class from the existing class.
The new class will have the features of both the old and the
derived new class. The base class is reused.
Reusability is achieved using inheritance. Inheritance and
reusability are not different from each other. The outcome of
inheritance is reusability.
The base class is also called superclass, parent, or ancestor, and
the derived class is called subclass, child, or descendent. It is also
possible to derive a class from a previously derived class. A class
can be derived from more than one class.
ACCESS SPECIFIERS AND SIMPLE INHERITANCE

The public members of a class can be accessed by an


object directly outside the class. Directly means when
objects access the data member without the member
function of the class. The private members of the class
can only be accessed by the public member function of
the same class.
 The protected access specifier is the same as private.
The only difference is that it allows its derived classes
to access the protected members directly without the
member functions. This difference is explained later
with suitable examples.
Public Inheritance

The class can be derived either publicly or privately. No third type exists.
When a class is derived publicly, all the public members of the base class can
be accessed directly in the derived class.
However, in private derivation, an object of the derived class has no
permission to directly access even public members of the base class. In such a
case, the public members of the base class can be accessed using public
member functions of the derived class.
In case the base class has private member variables and a class derived
publicly, the derived class can access the member variables of the base class
using only member functions of the base class.
The public derivation does not allow the derived class to access the private
member variable of the class directly as is possible for public member
variables.
The following example illustrates public inheritance where base class
members are declared public and private.
int main()
// PUBLIC DERIVATION // {
class A      // BASE CLASS clrscr();
{ B b;              // DECLARATION
OF OBJECT
public:
b.x=20;
int x; b.y=30;
}; cout<<“\n member of A:”<<b.x;
class B: public A       // cout<<“\n Member of B:”<<b.y;
DERIVED CLASS return 0;
{ }
public: OUTPUT
int y; Member of A : 20
}; Member of B : 30
In the above program, two classes are defined, and each contains one
public member variable. The class B is derived publicly from the class A.
Consider the following statement:
class B : public A
The above statement is used to derive the new class. The keyword public is
used to derive the class publicly. The access specifier is followed by the
name of the base class.
In function main(), b is an object of class B. The object b can access the
members of class A as well as of class B through the following statements:
b.x=20; // Access to base class members
b.y=30; // Access to derived class members
Thus, the derived class holds the members of the base class, and its object
has the permission to access the members of the base class.
 class A      // BASE CLASS

{
private: void show()
int x; {
public:
showx();
A() {x=20;}
void showx()
cout<<“\n y=”<<y;
{ }
cout<<“\n x=”<<x; };
}
int main()
};
{
class B : public A    // DERIVED CLASS
{ clrscr();
public: B b;      // DECLARATION OF
int y; OBJECT
B() {y=30;} b.show();
return 0;
}
OUTPUT
x=20
y=30
In the above program, the class A has one private member, default constructor, and member
function showx(). The class B is derived from the class A publicly. The class B contains one public
member variable y, default constructor, and member function show().
In function main(), b is an object of the derived class B. Though the class B is derived publicly from
the class A, the status of the members of the base class remains unchanged. The object b can access
public members, but cannot access the private members directly. The private members of the base
class can be accessed using the public member function of the base class.
The object b invokes the member function show() of the derived class. The function show() invokes
the showx() function of the base class.
The object b can access the member function defined in both base and derived classes. The
following statements are valid:
b.showx(); // Invokes member function of base class
b.show(); // Invokes member function of derived class
The constructor and member functions of the derived class cannot access the private members. Due to
this, separate constructor and member functions are defined in both base and derived classes.
Private Inheritance

The objects of the privately derived class cannot


access the public members of the base class directly.
Hence, the member functions are used to access the
members.
Write a program to derive a class privately. Declare the member of base class
under public section.

// PRIVATE INHERITANCE // void show()


#include<iostream.h>
{cout<<“\n x=”<<x;
#include<constream.h>
class A    // BASE CLASS cout<<“\n y=”<<y;
{ }
public: };
int x;
int main()
};
class B : private A    // DERIVED CLASS {
{ clrscr();
public: B b;    // DECLARATION OF
int y; OBJECT
B()
b.show();
{x=20;
y=40; return 0;
} }
OUTPUT
x=20
y=40
Explanation: In the above program, the class B is derived
privately from the class A. The member variable x is a public
member of the base class. However, the object b of the derived
class cannot directly access the variable x. The following
statements are invalid:
b.x=30; // cannot access
The class B is derived privately. Hence, its access is restricted.
The member function of the derived class can access the
members of the base class. The function show() does the same.
Write a program to derive a class privately.

class A    // BASE CLASS void show()


{ {
int x;
showx();
public:
cout<<“\n y=”<<y;
A()
{x=20;}
}
void showx() };
{ int main()
cout<<“\n x=”<<x; {
} clrscr();
};
B b;      // DECLARATION OF OBJECT
class B : private A // DERIVED CLASS
b.show();
{
public: return 0;
int y; }
B()
{ y=40;
}
OUTPUT
x=20
y=40
Explanation: In the above program, the member variables of the base class
and derivation methods are private. The derived class and its objects cannot
access the private members of the base class directly. Hence, separate
constructor and member functions are defined in both base and derived
classes. The object b invokes the member function show() to display the
members. The constructors are used to initialize the member variables.
However, while accessing the private data, difficulties are faced by the
programmer, because they cannot be accessed without the member
functions. Even the derived class has no permission to access the private
data directly. Hence, the programmer needs to define separate
constructor and member functions to access the private data of that
particular base class. Due to this, the length of the program is increased.
PROTECTED DATA WITH PRIVATE INHERITANCE

The member function of the derived class cannot


access the private member variables of the base class.
The private members of the base class can be accessed
using the public member function of the same class.
This approach makes the program lengthy. To
overcome the problems associated with private data,
the creator of C++ introduced another access
specifier protected.
The protected is similar to private, but it allows the
derived class to access the private members directly.
class A     // BASE CLASS void show()
{ {
protected:    // protected declaration cout<<“\n x=”<<x;
int x; cout<<“\n y=”<<y;
}; }
class B : private A    // DERIVED };
CLASS int main()
{ {
int y; clrscr();
B b;     // DECLARATION OF
public:
OBJECT
B()
b.show();
{ x=30; return 0;
y=40; }
}
OUTPUT
x=30
y=40
Explanation: In this program, the data member variable of class A is declared under
the protected section. The class A contains neither default constructor nor any
member function. The class b is derived from class A. The member function of the
derived class B can access the protected member of the base class.
Thus, the protected mechanism reduces the program size. The derived class need not
depend on the member function of the base class to access the data. The protected
data safeguard the data from direct use and allow only the derived classes to access
the data.
The protected access specifier should be used when it is known in advance that a
particular class can be used as a base class. The data members of the classes that can
be used as a base class should be declared as protected. In such classes, the
programmer need not define functions. The member functions of the base class are
rarely useful.
In the inheritance mechanism, the derived classes have more
number of members as compared with the base class.
 The derived class contains the properties of a base class and a
few of its own. The object of the derived class can access the
members of both base and derived classes. However, the object
of the base can access the members of only the base class and not
any of the derived class, as shown in Figure .
 Hence, the programmer always uses objects of the derived
classes and performs operations. The member function of the
base class cannot access the data of the derived class. Obviously,
the programmer uses the object of the derived classes and
possibly avoids defining the member function in the base class.
Access specifiers with their scope
(a) Single Inheritance
Multiple Inheritance
(c) Hierarchical Inheritance
(d) Multilevel Inheritance
(e) Hybrid Inheritance
(f) Multipath Inheritance
SINGLE INHERITANCE

When only one class is derived


from a single base class, such a
derivation of a class is known
as single inheritance; further, the
derived class is not used as a base
class. This type of inheritance uses
one base and one derived class.
The new class is termed derived
class, and the old class is
called base class, as shown in fig. A
derived class inherits data member
variables and functions of the base
class. However, constructors and
destructors of the base class are not
inherited in the derived class.
class ABC void show()
{
protected: {
char name[15]; cout<<“\n Name:”<<name <<“\n
int age;
Age:”<<age<<“ Years”;
cout<<“\n Height:”<<height <<“ Feets”<<“\n
};
Weight:”<<weight <<“Kg.”;
class abc : public ABC // public derivation
}
{ };
float height; int main()
float weight; {
public: clrscr();
void getdata() abc x;
{ cout<<“\n Enter Name and Age:”; x.getdata(); // Reads data through keyboard.
cin>>name>>age; x.show(); // Displays data on the screen.
cout<<“\n Enter Height and Weight:”; return 0;
cin>>height >>weight; }
}
OUTPUT The class abc is derived
Enter Name and Age : Santosh 24
from class ABC. The
Enter Height and Weight : 4.5 50
Name : Santosh
statement class abc: public
Age : 24 Years ABC defines the
Height : 4.5 Feets derived class abc. In
Weight : 50 Kg. functionmain(), x is an
Explanation: In the above program, object of the derived class
the two classes ABC and abc are abc. The object x invokes
declared. The class ABC has two
protected data
the member
members, name and age. The class functiongetdata() and
abc has two float data show(). This function reads
members, heightand weight with a
two-member
and displays data,
function getdata() and show(). respectively.
MULTILEVEL INHERITANCE
The procedure of deriving a class
from a derived class is
called multilevel inheritance.
In the above figure, class A3 is
derived from class A2. The class
A2 is derived from class A1.
The class A3 is a derived class.
The class A2 is a derived class as
well as a base class for class A3.
The class A2 is called
an intermediate base class. The class
A1 is a base class ofclasses
A2 and A3. The series of classes A1,
A2, and A3 is called an inheritance
pathway, as shown in Fig .
// Multilevel inheritance // void get() // Reads data
#include<iostream.h>
{
#include<constream.h>
class A1 // Base class cout<<“Name:”; cin>>name;
{ cout<<“Age:”; cin>>age;
protected: cout<<“Salary”; cin>>salary;
char name[15];
cout<<“Height:”; cin>>height;
int age;
}; cout<<“Weight:”; cin>>weight;
class A2 : public A1 // Derivation first level }
{ void show() // Displays data
protected:
{
float height;
float weight; cout<<“\nName:” <<name;
}; cout<<“\nAge:” <<age <<“ Years”;
class A3 : public A2 // Derivation second level cout<<“\nSalary:” <<salary;
{
cout<<“\nHeight:” <<height <<“ Feets”;
protected:
char salary cout<<“\nWeight:” <<weight <<“ Kg.”;
public: } };
int main() OUTPUT
Name : Balaji
{
Age : 26
clrscr();
Sex : M
A3 x; // Object Height : 4
Declaration Weight : 49.5
x.get(); // Reads data Name : Balaji
x.show(); // Displays data Age : 26 Years
return 0; Salary:2000

} Height : 4 Feets
Weight : 49.5 Kg.
MULTIPLE INHERITANCE

Multiple inheritance is a latest


addition to the C++ language.
When a class is derived from
more than one class, this type
of inheritance is
called multiple inheritance.
A class can be derived by
inheriting the properties of
more than one class. Properties
of various pre-defined classes
are transferred to a single
derived class. Figure shows
multiple inheritance.
// Multiple Inheritance // public:
#include<iostream.h> void getdata()
{
#include<constream.h> cout<<“\n Enter values of a,b,c & d & e:”;
class A {protected: int a;}; // class A cin>>a>>b>>c>>d>>e;
declaration }
class B {protected: int b;}; // class B
declaration void showdata()
{
class C {protected: int c;}; // class C
cout<<“\n a=”<<a <<“ b=”<<b <<“ c = ”<<c <<“ d=
declaration ”<<d <<“ e=”<<e;
class D {protected: int d;}; // class D }
declaration };
int main()
// class E : public A, public B, public C, public
{
D
clrscr();
class E : public A,B,C,D // Multiple derivation E x;
{ x.getdata(); // Reads data
x.showdata(); // Displays data
int e;
return 0;
}
OUTPUT
Enter values of a,b,c &
d & e : 1 2 4 8 16
a=1 b = 2 c = 4 d= 8 z=
16
 HIERARCHICAL INHERITANCE

We learned that in inheritance, one


class could be inherited from one or
more classes. In addition, new
members are added to the derived
class.
The inheritance also supports the
hierarchical arrangement of a
program. Several programs require
the hierarchical arrangement of
classes, in which derived classes
share the properties of the base
class.
A hierarchical unit exhibits top-
down style through splitting a
compound class into several simple
subclasses. :
class red class green : public blue, public
{ public: yellow
red() {cout<<“Red”;}; { public:
}; green() {cout<<“=Green”;}
class yellow };
{ public:
class violet : public red, public blue
yellow() {cout<<“Yellow”;}
{ public:
};
class blue
violet() {cout<<“=Violet”;}
{ public: };
blue() {cout<<“Blue”;} class reddishbrown : public orange,
}; public violet
class orange : public red, public yellow { public:
{ public: reddishbrown()
orange() {cout<<“=Orange”;} }; {cout<<“=Reddishbrown”;}
};
class yellowishbrown : public int main()
green, public orange
{
{
public: clrscr();
yellowishbrown() reddishbrown r;
{cout<<“=Yellowishbrown”;}
endl(cout);
};
class bluishbrown : public violet,
bluishbrown b;
public green endl(cout);
{ yellowishbrown y;
public:
endl(cout);
bluishbrown()
{cout<<“=Bluishbrown”;} return 0;
}; }
For each color, a separate class with
constructors is declared. The classes red, blue,
OUTPUT
and yellow are base classes. The class orange
is derived from red and yellow. The class
Red Yellow = Orange
green is derived from blue and yellow. The
class violet is derived from red and blue. Red Blue = Violet =
The class reddishbrown is derived from
orange and violet; the class yellowishbrown is
Reddishbrown
derived from green and orange; and, lastly, the Red Blue = Violet Blue
class bluishbrown is derived from violet and
green.
In function main(), objects of the classes
Yellow = Green =
reddishbrown, yellowishbrown, and Bluishbrown
bluishbrown are declared. When the objects
are declared, constructors are executed from Blue Yellow = Green
the base to derived classes. When executed,
the constructor displays the class name (color Red Yellow = Orange =
name). The output shows the names of
different colors and resulting colors after their Yellowishbrown
combination.
HYBRID INHERITANCE

A combination of one or more


types of inheritance is known
as hybrid inheritance.
Sometimes, it is essential to
derive a class using more types
of inheritance.
 Figure 11.10 shows hybrid
inheritance. In the below given
diagram, the class game is
derived from two base classes,
that is, location and physique. 
The class physique is also
derived from the class player.
class PLAYER class GAME : public PHYSIQUE, LOCATION
{ {
protected: protected:
char name[15]; char game[15];
char gender; public:
int age; void getdata()
};
{
class PHYSIQUE : public PLAYER
cout<<“Enter Following Information\n”;
{
cout<<“Name:”; cin>>name;
protected:
cout<<“Gender:”; cin>>gender;
float height;
float weight; cout<<“Age:”; cin>>age;
}; cout<<“Height:”; cin>>height;
class LOCATION cout<<“Weight:”; cin>>weight;
{ cout<<“City:”; cin>>city;
protected: cout<<“Pincode:”; cin>>pin;
char city[10]; cout<<“Game:”; cin>>game;
char pin[7]; }
};
void show() int main()
{ {
cout<<“\n Entered Information”; clrscr();
cout<<“\nName:”; cout<<name;
cout<<“\nGender:”; cout<<gender; GAME G;
cout<<“\nAge:”; cout<<age; G.getdata();
cout<<“\nHeight:”; cout<<height;
cout<<“\nWeight:”; cout<<weight; G.show();
cout<<“\nCity:”; cout<<city; return 0;
cout<<“\nPincode:”; cout<<pin;
cout<<“\nGame:”; cout<<game; }
}
};
OUTPUT  In the above
Enter Following Information program, player, physique, location, and
Name : Mahesh  game classes are defined. All the data
Gender : M members of these four classes are
Age : 25 protected. The class physique is derived
Height : 4.9 from thebase class player.
Weight : 55
 The class game is derived
City : Nanded
Pincode : 431603 from physique and location; that is, the
Game : Cricket derived class game has two base
Entered Information classes physique and location. 
Name : Mahesh  The location is a separate class and is
Gender : M not derived from any other class.
Age : 25
Height : 4.9
Weight : 55  The getdata() and show() are functions
City : Nanded of class game and reads and display
Pincode : 431603 data, respectively. In main(), the
Game : Cricket object G of class game calls these
functions one by one to read and write
the data. The output of the program is
shown at the end of the above program.
MULTIPATH INHERITANCE

When a class is derived


from two or more classes,
those are derived from the
same base class. Such a type
of inheritance is known
as multipath inheritance.
The multipath inheritance
also consists of many types
of inheritance, such as
multiple, multilevel, and
hierarchical, as shown in
 Figure 11.11
class A1 In the above example,
classes A2 and A3 are derived from
{ protected:
class A1; that is, their base class is
int a1; }; similar to class A1 (hierarchical
class A2 : public A1 inheritance). Both classes
A2 and A3 can access the variable a1 of
{ protected: class A1.
int a2;};  The class A4 is derived from classes

class A3: public A1 A2 and A3 by multiple inheritance. If


we try to access the variable a1 of
{ protected: int a3; class A1, the compiler shows error
}; messages as given below.
class A4: public A2,A3
Error PRG58.CPP 30: Member is
{ int a4;
ambiguous: ‘A1::a1’ and ‘A1::a1’
}; Error PRG58.CPP 37: Member is
ambiguous: ‘A1::a1’ and ‘A1::a1’
In the above example, we
can observe all types of
inheritance, that
is, multiple, multilevel, and
hierarchical.
The derived class A4 has
two sets of data members
of class A1 through the
middle base
classes A2 and A3.
The class A1 is inherited
twice.
VIRTUAL BASE CLASSES

To overcome the


ambiguity occurring due
to multipath inheritance,
the C++ provides the
keyword virtual. 
Thekeyword virtual decl
ares the specified classes
virtual. The example
given below illustrates
the virtual classes:
class A1 class A3: virtual public A1 //
{ virtual class declaration
protected: {
int a1; protected:
}; int a3;
class A2 : virtual public A1 // };
virtual class declaration class A4: public A2,A3
{ {
protected: int a4;
int a2; };
};
When classes are declared as A base class cannot be
virtual, the compiler takes specified more than once
essential caution to avoid the
duplication of member variables. in a derived class.
Thus, we make a class virtual if  class A
it is a base class that has been {------
used by more than one derived ------};
class as their base class.
Consider another example that
class A1: A, A
{...}; // Illegal Declaration
will give you a clear idea of
virtual classes as well as the Here, class A is specified
necessary care to be taken while twice. Hence, it is an
declaring virtual classes. illegal declaration.
A base class can be indirectly The case (b) causes problems.
passed to the derived class To avoid duplication, we can
more than once. add the keyword virtual to a
base class specifier.
 
class L: public A {...} For example,
class K: public A {...} class L: virtual public A {...}
class J: public L, public K class K: virtual public A {...}
{...} // Legal declaration class J: public K, public J {...}
In the above case (b), each The keyword virtual always
object of class J will contain appears before the class
two sub-objects of class A name. A is now a virtual base
through classes L and K. class, and class J has only one
sub-object of class A.
class A1
class A3 : public virtual A1 // virtual
{
declaration
protected: {
int a1; protected:
}; int a3;
};
class A2 : public virtual A1 // virtual
class A4 : public A2,A3 // virtual declaration
declaration
{
{ int a4;
protected: public:
int a2; void get()
{
};
cout<<“Enter values for a1, a2,a3 and a4:”;
cin>>a1>>a2>>a3>>a4;
}
void put()
{
cout<<“a1=”<<a1 <<“a2=”<<a2
<<“a3=”<<a3 <<“a4=”<<a4;
}
};
int main()
{
clrscr();
A4 a;
a.get(); // Reads data
a.put(); // Displays data
return 0;
}
class Base int main()
{ public: void show() { Base b; //Base class
{ cout << "Base class\t"; } object
}; Derived d; //Derived class
class Derived:public Base object
{ public: void show() b.show(); //Early Binding
{ cout << "Derived Ocuurs
Class"; } } d.show(); }
Function Call Binding using Base class Pointer

class Base int main()


{ public: void show() { Base* b; //Base class
{ cout << "Base class"; pointer
} }; Derived d; //Derived class
class Derived:public Base object
{ b = &d; b->show(); //Early
public: void show() Binding Occurs }
{
cout << "Derived Class";
}}

You might also like