CH. 5 Inheritance
CH. 5 Inheritance
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
Introduction :
• Inheritance is a form of software reusability in which new classes are
created from existing classes by absorbing their attributes and behavior
and overriding these with capabilities the new classes requires.
• Inheritance is the process by which one object can acquire the
properties of another object.
• Inheritance is the process of creating new classes from existing class.
• The existing class is known as base class and the newly created class is
called as a derived class.
• The derived class inherits all capabilities of the base class.
• A derived class is more specific than its base class and represents a
smaller group of objects.
• For example, a Red Delicious apple is part of the classification apple,
which in turn is part of the fruit class. Hence, inheritance supports the
concept of classification; with the help of classification, an object
need to define only those qualities that makes it unique within its
class.
• Fig.: ‘Shape’ Hierarchy
Shape
1) Public Inheritance
This is the most used inheritance mode. In this the protected member of super
class becomes protected members of sub class and public becomes public.
2) Private Inheritance
In private mode, the protected and public members of super class become private
members of derived class.
Types of Inheritance :
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. Single Inheritance :
• When one base class is derived by one child class, then it is known as single
inheritance.
• The existing base class is known as direct base class whereas, they newly
created class is called as singly derived class. As shown in Fig. :
• Single Inheritance is the most primitive among all the types of inheritance in
C++. In this inheritance, a single class inherits the properties of a base class.
All the data members of the base class are accessed by the derived class
according to the visibility mode (i.e., private, protected, and public) that is
specified during the inheritance.
#include <iostream>
{public:
Computer()
{ cout << "I am a computer.\n\n"; }
};
int main()
{ Computer obj;
return 0; }
class base_class_1
{ // class definition };
class derived_class: visibility_mode base_class_1
{ // class definition };
Example :
Suppose a college want to store information of undergraduate (UG) and
Postgraduate students (PG). Both are having registration number , name
and address. Each postgraduate student also have additional attributes
along with above attributes areUGStudent
placement company name.
As shown in Fig. :- Regno
Name
address
PGStudent
Companyname
• Program to illustrate single inheritance.
#include<iostream.h>
using namespace std;
class student
{
protected :
int regno;
char name[20];
char addr[30];
public :
void getdata()
{ cout<<“Enter registration no, name and address ”;
cin>>regno>>name>>addr;
}
void display() void dispPG()
{ {
cout<<“registration no. =”<<regno; cout<<“\n Registration no. =”<<regno;
cout<<“name = ”<<name; cout<<“\n Name =”<<name;
cout<<“address = ”<<addr; cout<<“\n Address =”<<addr;
} cout<<“\n Company name
=”<<compname;
};//end of base class
}
class PGstudent : public student
};
{ int main()
private : {
char compname[20]; student s;
public : PGstudent ps;
void get_PG_data() s.getdata();
{ s.display();
getdata(); ps.get_PG_data();
ps.dispPG();
cout<<“\n Enter the Company name :”;
}
cin>>compname;
}
}
• Output :-
Enter registration no , name and address
10 Ram Pune
registration no = 101 name = Ram addr = Pune
Enter registration no , name and address
402 Sita Pune
Enter Company Name = Zenex
registration no = 402
name = Sita
address = Pune
Company Name = Zenex
• Program : A base class contains the data of employee name, empno and
Gender. The derived class has been declared as an array of class objects.
The Program illustrate the Single inheritance.
class derived : public base
#include<iostream.h>
{
class base private :
float bsalary;
{ public:
private : void get();
void disp();
char name[20]; };
int empno; void base :: get()
{
char gender; cout<<“\n Enter name :”;
Public : cin>>name;
cout<<“\n Enter Employee id :” ;
void get(); cin>>empno;
void disp(); cout<<“\n Enter Gender :”;
cin>>gender;
}; }
void base:: disp()
void main()
{ {
cout<<“name =”<<name; derived ob[10];
cout<<“Emp no. is =”<<empno; int i,n;
cout<<“Gender =”<<gender; cout<<“How many employees ?”;
cin>>n;
} for(i=0;i<n;i++)
void derived:: get() {
{ ob[i].get();
base:: get(); }
cout<<endl;
cout<<“Enter basic salary :\n”;
cout<<“Name empno gender bsalary \
cin>>bsalary; n”;
} for(i=0;i<n;i++)
void derived:: disp() {
ob[i].disp();
{
cout<<endl;
base::disp(); }
cout<<“basic salary =”<<bsalary; }
}
Output :
How many employees? 2
Enter name: Prajakta
Enter Employee id :101
Enter Gender :f
Enter basic salary : 10000
Enter name: Pratik
Enter Employee id : 102
Enter Gender :m
Enter basic salary :40000
name empno gender bsalary
Name=Prajakta Empno is = 101 sex=f basic salary=10000
Name=Pratik Empno is = 102 sex=m basic salary=40000
2. Multilevel Inheritance :-
child class 2
• Syntax of multilevel inheritance :
class base
{ ………….
…………
};
class child1: public base
{ ……………….
……………….
};
class child2: public child1
{ ……………………….
……………………….
};
• Consider an example of bank. In bank, different customers have
savings account. Some customers may have taken loan from the bank.
So the bank always maintains information about bank depositors and
borrowers. This can be shown using the following Fig. :
customer
name
phone_no
depositor
account_no
balance
borrower
loan_no
Loan_amount
• Program to illustrate use of multilevel inheritance.
#include<iostream.h>
using namespace std; void get_depositor_data()
{
class customer //base class cout<<“\n Enter nme & phone no”;
{ cin>>name>>phone_no;
cout<<“\n Enter account no and
protected: balance”;
char name[30]; cin>>account_no>>balance;
}
int phone_no;
void display_depositor_data()
}; //end of base class {
class depositor: public customer//child class1 cout<<“\n Name = ”<<name;
cout<<“\n Phone no =”<<phone_no;
{ cout<<“\n Account no =”<<account_no;
private : cout<<“\n Balance = ”<<balance;
}
int account_no; }; //end of child class1
float balance;
public :
class borrower : public depositor //child class2
{
protected :
int loan_no;
float loan_amount;
public :
void get_loan_data()
{
cout<<“\n Enter loan no and loan amount”;
cin>>loan_no>>loan_amount;
}
void display_loan_data()
{
cout<<“\n Loan no = ”<<loan_no;
cout<<“\n Loan amount =”<<loan_amount;
}
};
int main()
{
int choice;
cout<<“1-Read & display depositor information ”<<endl;
cout<<“2-Read & display depositor & borrower information”<<endl;
cout<<“Enter your choice =” ;
cin>>choice;
switch(choice)
{
case 1:
depositor d;
d.get_depositor_data();
d.display_depositor_data();
break;
case 2: Output :-
borrower b; 1- Read & display depositor information
2- Read & display depositor & borrower
b.get_depositor_data(); information
b.get_loan_data(); Enter your choice = 1
Enter name & phone no Prajakta 98776677
b.display_depositor_data(); Enter account no and balance 123456789
b.display_loan_data(); 10000
break; Name = Prajakta
Phone no = 98776677
} Account no = 123456789
}// end of main Balance = 10000
• In this program, though the data members of depositor class are
private, they can accessed indirectly by the borrower class through
the member functions of the depositor class indirectly.
• Consider the example of student data. Base class is student. Class test is intermediate base class and
result is child class. The class result inherits the details of marks obtained in the test and the roll no.
of student from base class through multilevel inheritance.
#include<iostream.h> class test : public student
{
using namespace std;
protected :
class student int mark1, mark2;
{ public :
protected : void getmark(int a, int b)
{
int roll; mark1 = a;
public : mark2 = b;
void get(int x) }
void dispmark()
{
{
roll = x; cout<“mark1 = \n”<<mark1<<“mark2=\n”<<mark2;
} }
void display() };
{
cout<<“roll=”<<roll;
}
};
class result: public test int main()
{ {
result r;
private:
r.get(10);
int total; r.getmark(60,75);
public: r.displayall();
void displayall() }
Output:
{
total = mark1 + mark2; roll = 10
display(); mark1 = 60
mark2 = 75
dispmark(); total = 135
cout<<“total=” <<total;
}
};
3. Multiple Inheritance :-
• When more than one base classes are inherited by a derived class, then such
type of inheritance is called as multiple inheritance.
• The inheritance in which a class can inherit or derive the characteristics of
multiple classes, or a derived class can have over one base class, is known as
Multiple Inheritance.
• It specifies access specifiers separately for all the base classes at the time of
inheritance. The derived class can derive the joint features of all these classes
and the data members of all the base classes are accessed by the derived or
child class according to the access specifiers.
• Fig. : Multiple Inheritance
• Example : A child inherits the features from father and intelligence
form mother.
Mother Father
Intelligence Features
Child
Features Intelligence
}
Ambiguity in Multiple Inheritance :
• One common cause of ambiguity in multiple inheritance is when two or
more base classes have methods with the same name, while there is no
method of that name in the derived class.
• In this case objects of the derive class have no way of knowing which of
the parent method is to be executed. The scope resolution operator can
be used to resolve the ambiguity.
• Another element of ambiguity in multiple inheritance arises when two
or more derived classes inherit the same member from a common base
class. If now another derived class inherits from these classes, two
copies of the original member function could be inherited.
• Fig. shows one possible scenario that leads to inheritance of multiple
copies.
Base1
Method(1)
Derived1 Derived 2
Method1() Method1()
Derived3
Method1()
Method1()???
test sports
result
Derived class
• When a class inherits another, the member of the base class becomes members of the
derived class.
• The Syntax of derived class definition is as follows :
class <derived_class_name >: <access modifier> <base_class_name>
{
//body of class
};
It contains:
• Keyword class
• Derived class name which is user defined name for new class.
• The : (colon) indicates that the derived_class_name is derived from the
base_class_name.
• The access modifier is optional. If no access modifier is present, the access
modifier is private by default . If written, then it must be public, private or
protected.
• base_class_name is the existing class name.
• Example:-
class base class derived:base //by default private
{…………………………. derivation
{ ………………………..
………………………….. ……………………….
}; };
class derived1: private base //private derivation
{
………………….
};
class derived2: public base //public derivation
{
………………….
};
class derived2: protected base //protected derivation
{
………………….
};
• Public Derivation :
• When the access modifier for a base class is public, all public
members of the base class become public members of the derived
class and all protected members of the base class becomes protected
members of the derived class.
• The members of derived class can access members of the base class if
the base class members are public or protected. They can not access
private members.
• The Fig. shows the base and derived class relationship.
Private
Class derived : public base
Protected
Protected
Access member
function of base Public
Derived object
Private
Protected
Access member
function of base
Base object Public Protected
Public
Not possible to access the
member function of base
class Derived object
• Program for private derivation.
#include<iostream.h>
using namespace std;
class Engine
{
public :
Engine(int nc)
{cylinder = nc;
}
void start()
{
cout<<getcylinder()<<“Cylinder engine started ”<<endl;
}
int getCylinder()
{
return cylinder;
}
private:
class Car : private Engine
{
public:
Car(int nc = 4): Engine(nc){ }
void start()
{
cout<<“car with ”<<Engine::getCylinder()<<“cylinder engine started ”<<endl;
Engine::start();
}
};
int main() • In this program, derived class object cannot access
{ the functions of base class because they become
private.
Car c(8); • But the public functions of base class access by public
c.start(); functions of derived class.
return 0;
}
Output:
car with 8 cylinder engine started
8 cylinder engine started
• Protected Members :
• The protected keyword provides greater flexibility in the inheritance
mechanism.
• When a member of a class is declared as protected, that member is
not accessible by other, non-member elements of program.
• Protected members are as good as private members within the class.
• Protected member differs from private members when a protected
member is inherited. Using the access modifier protected in base
class, we could make available the data member in the derived class
and restrict its access in other classes or in main().
• Protected members of base class can be access in derived class.
class base
private
Class derived :public class
protected
protected
Access
members
Access members public
Derived object
• Data member declare as protected within a base class is
accessible by the member within its class and any class
immediately derived from it.
• Fig. shows the public derivation with protected data
members.
• If the base class is inherited as public, then the base class
protected member becomes protected member of derived
class and therefore, can be accessed by derived class.
• Thus, by using protected, we can create class members that
are private to their class but can still be inherited and
accessed by a derived class.
• Program using protected members.
#include<iostream.h>
using namespace std;
class base
{
protected :
int I,j; //private to base, but accessible by derived class
public :
void getij()
{
cout<<“\n Enter value of i and j”;
cin>>i>>j;
}
void show()
{
cout<<“i=”<<i<<“ “<<“j=”<<j<<“\n”;
}
};
class derived2: public derived1
class derived1 : public base {
int x;
{ public:
int k; void get()
{
public: getij();
x=i*j;
void getdata() } //can access I and j since public inheritance
{ void show()
{
getij(); cout<<“x=”<<x;
k=i*j; }
}; //end of class derived2
} int main()
{
void showx() derived1 ob1;
{ derived2 ob2;
ob1.getdata();
cout<<“k=”<<k; ob1.showlal() ;
ob2.get();
}
ob2.showx();
}; //end of class derived1 }
• Output:
Enter value of i and j 10 20
K=200
Enter value of i and j 15 10
K=150
• In above program, if derived1 class inherits base class privately, then
protected member of base becomes private members of derived1
class which cannot inherited in derived2 class.
• So, when a protected member is inherited in public mode, it
becomes protected in the derived class and therefore it is accessible
by the member function of the derived class. It is also inherited
further.
• A Protected member inherited in the private mode becomes private
in the derived class and cannot be inherited further.
• Protected Derivation :-
• C++ allows us to use protected as access modifier.
• When access modifier is protected, all public and protected members of the base class become protected
members of the derived class.
• Program for protected derivation.
#include<iostream.h>
using namespace std;
class base
{
protected :
int i, j; //private to base but accessible in derived
public :
void getij()
{
cin>>i>>j;
}
void show()
{
cout<<i<<“ “<<j<<“\n”;
}
class derived: protected base int main()
{ {
derived ob;
int k; //ob.getij() //illegal; getij() is protected member of
public: derived
void getdata() ob.getdata(); //correct as public member of derived
ob.showall(); //correct as public member of derived
{
//ob.show(); //illegal
getij(); }
k = i*j; //derived may access base Output:
2 3
protected data members
6 2 3
}
void showall()
{
cout<<k<<“ “;
show();
}
};
• In this program, getij() and show() are public members of base, but
they become protected members of derived. Using derived object is
not accessible .
• Summary about Access Specifiers :
• Table : Access in a Derived Class
Derived class
Base class members Public derivation Private derivation Protected
derivation
Private Not accessible Not accessible Not accessible
Protected Protected Private protected
Public Public Private protected
• Virtual Base Class :-
• Consider a situation where multilevel, multiple and hierarchical all the
three kinds of inheritance are involved. As shown in fig. :
• Fig. : Multipath inheritance
base
derived1 derived2
derived3
• In this fig., the base class is inherited by both derived1 and derived2.
derived3 directly inherits both derived1 and derived2.
• All the public and protected members of Base are inherited into
derived3 twice through both derived1 and derived2.
• Therefore, derived3 would have duplicate sets of members inherited.
This causes ambiguity when a member of Base is used by derived3.
• To resolve this ambiguity, C++ includes a mechanism by which only
one copy of Base will be included in derived3. This feature is called a
virtual base class. When a class is made virtual, C++ take necessary
care to inherit only one copy of that class.
• The keyword virtual precedes the base class access specifier when it is
inherited by a derived class.
• The situation in Fig. can be declared as :
Class base
{……………};
Class derived1:virtual public Base
{…………..};
Class derived2: virtual public Base
{……………};
Class derived3: public derived1, public derived2
{……………};
class derived2: virtual public base
• Program using virtual base class. {
public:
#include<iostream.h> int z;
};
using namespace std; /*derived3 inherits derived1 and derived2.
However, only one copy of base is present. */
class base class derived3: public derived1, public derived2
{ {
public :
public: int mult()
{ return x*y*z;};
int x; };
void main()
}; {
derived3 d;
class derived1: virtual public base d.x = 10;
{ d.y = 20;
d.z = 30;
public : cout<<“Product is”<<d.mult();
}
int y; Output :
Product is 6000
};
• Note :
• If derived1 and derived2 classes had not inherited base as virtual,
then statement d.x = 10; becomes ambiguous and a program would
have resulted as compile-time error.
• If virtual base classes are used when an object inherits the base more
than once, only one base class is present in the object.
• If normal base classes are used when an object inherits the base more
than once, the multiple copies will be found; and it is compile error.
• Program: To calculate the total marks of a student using the concept of virtual base class.
#include<iostream.h>
using namespace std;
class student
{
int rno;
public:
void getnumber()
{
cout<<“Enter Roll No.”;
cin>>rno;
}
void putnumber()
{
cout<<“\n\n Roll No. :”<<rno<<“\n”;
}
};
class test : virtual public student
{ class sports : public virtual student
public : {
int part1, part2; public :
void getmarks() int score;
{ void getscore
cout<<“Enter Marks\n”; {
cout<<“Part1 :” ; cout<<“Enter Sports Score :”;
cin>>part1; cin>>score;
cout<<“Part2 :”; }
cin>>part2; void putsccore()
} {
void putmarks()
cout<<“\n\t Sports score is :”<<score;
{
}
cout<<“\t Marks Obtained \n”;
};
cout<<“\n\t Part1 :”<<part1;
cout<<“\n\tPart2 :”<<part2;
}
};
class result : public test , public sports int main()
{
{ result obj;
obj.getnumber();
int total; obj.getmarks();
public: obj.getscore();
obj.display();
void display() }
Output:
{ Enter Roll No.:151
total = part1 + part2 +score; Enter Marks
Part1: 90
putnumber(); Part2: 80
Enter sports score :80
putmarks(); Roll No. :151
putscore(); Marks Obtained
Part1 : 90
cout<<“\n\t Total Score :”<<total; Part2 : 80
Sports Score is :80
} Total Score is : 250
};
Abstract Class :-
• A class that contains at least one pure virtual function is said to be
abstract. A pure virtual function is a member function i.e., declared in
an abstract class, but defined in a derived class.
• An abstract class does not create any object and it contains one or
more functions for which there is no definition(i.e., pure virtual
function) .
• We can create pointers and references to an abstract class. This
allows abstract classes to support runtime polymorphism, which
depends upon base class pointers and references to select the proper
virtual function.
• An abstract class is used only to derive other classes. For example :
Shape is abstract base class which derives square, circle and rectangle.
• Following Program shows use of abstract classes.
#include<iosream.h>
using namespace std;
class Square : public Shape
//Abstract class
{
public :
class Shape
float calculateArea()
{
{ return l*l; }
protected:
};
float l;
int main()
public :
{
void getData() Square s;
{ Circle c;
cin>>l; cout<<“Enter length to calculate the area of a square :”;
} s.getdata();
//virtual function cout<<“Area of square :”<<s.calculateArea();
virtual float calculateArea() = 0; cout<<“\n Enter radius to calculate the area of a circle :”;
}; c.getData();
class circle: public Shape cout<<“Area of circle :”<<c.calculatearea();
{ return 0;}
public :
Output:
float calculateArea()
Enter length to calculate the area of a square : 4
Area of square : 16
{
Enter length to calculate the area of a circle : 5
return 3.14*l*l;
Area of circle : 78.5
Polymorphism:
• Polymorphism means “one name , many forms”.
• Polymorphism is the process of defining a number of objects at
different classes into group and call the method to carry out the
operation of the objects using different function calls.
• There are two types of polymorphism :
1. Compile time polymorphism :
• This is also called as early or static binding .Selection of an
appropriate function for a particular call at the compile time itself.
• For example, function overloading and operator overloading .
• Function overloading is also referred to as functional polymorphism.
• The same function can perform a wide variety of tasks.
• The same function can handle different data types. When many
functions with the same name but different argument lists are
defined ,then the function to be invoked corresponding to a function
call is known during compile time.
• When the source code is compiled, the functions to be invoked are
bound to the compiler during compile time, as to invoke which
function depending upon the type and number of arguments . Such a
phenomenon is referred to early binding, static linking or compile
time polymorphism.
2. Run-time polymorphism:
• This is also called as dynamic binding or late binding.
• Sometimes, a situation occurs where function name and prototype is same
in both the base class and in the derived class.
• Compiler does not know what to do, which function to call.
• In this class appropriate member function is selected to run time.
• For example, virtual function.
• Fig. : Types of Polymorphism Polymorphism
int main()
class electronicDevice
{ public: {
{ // block of statement(s)
}:
class B: public A // class B derived from a single class A -- follows single inheritance
{// block of statement(s)
};
class C
{// block of statement(s)
};
class D: public B, public C
// class D derived from two classes, class B and class C -- follows multiple inheritance
{
// block of statement(s)
};
#include <iostream> class Mammals: public Animals // indicates class B derived from
class A
using namespace std;
{
class Animals // indicates class A
public:
{
Mammals()
public:
{
Animals()
cout<< "This is a mammal\n";
{
}
cout<< "This is an animal\n";
};
}
};
class Cow: public Mammals, public Herbivores
class Herbivores // indicates class C
// indicates class D derived from class B and class C
{
{
public:
public:
Herbivores()
Cow()
{
{ cout<< "A cow is a herbivore mammal\n"; }
cout<< "This is a herbivore\n";
};
}
int main() {
};
Cow c;
return 0;
}
Virtual base class:
Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an
inheritance hierarchy when using multiple inheritances.
Need for Virtual Base Classes: Consider the situation where we have one class A . This class A is inherited by two other classes B
and C. Both these class are inherited into another in a new class D as shown in figure below.
As we can see from the figure that data members/function of class A are inherited twice to class D. One through class B and
second through class C. When any data / function member of class A is accessed by an object of class D, ambiguity arises as to
which data/function member would be called?
One inherited through B or the other inherited through C.
This confuses compiler and it displays error.
Virtual functions ensure that the correct function is called for an object, regardless
of the type of reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at runtime.
• Rules for Virtual Functions
public: // Derived 2
void getDimension() { class Circle : public Shape {
cin >> dimension; public:
} float calculateArea() {
return 3.14 * dimension * dimension;
// pure virtual Function }
virtual float calculateArea() = 0; };
};
int main() {
Square square;
Circle circle;
return 0;
}
Function Overriding
In this tutorial, we will learn about function overriding in C++ with the help of
examples.
Suppose, the same function is defined in both the derived class and the based
class. Now if we call this function using the object of the derived class, the
function of the derived class is executed.
class Base {
public:
void print() {
cout << "Base Function" << endl;
}
};
int main() {
Derived derived1;
derived1.print();
return 0;
}