You are on page 1of 62

Chapter 4 :Inheritance

J.P.Parmar
In this chapter , you will learns:
Inheritance:
• Introductions
• Defining Derived classes.
• Single inheritance and making members of the base class
privately inherited by
derived class
• Method overriding in the derived class
• making members of the base class publicly inherited by
derived class
• making members of the base class protected inherited by
derived class
• Multilevel and Multiple Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance, Virtual Base classes and Abstract Classes
• Constructors in Derived classes
• Member classes: Nesting of classes
Chapter 7 :Inheritance
2
j.p.parmar
Introduction:
• C++ supports concept of reusability. it means something already
exists and use it again rather than creating it again. It reduces the
time. In C++ , reusability is achieved by inheritance.
• Inheritance is the concept of deriving new class from an old
existing class. The new class is called a derived class or sub class
and existing class from which a new class is derived is called a
base class or super class.
• Inheritance is the mechanism for building a new class from
existing class and defining a new class to be specialization and
argumentation of existing class type.

Chapter 7 :Inheritance
3
j.p.parmar
For example, class A is base class and class B is a derived class then
pictorial representation is as follow:

Class A has its own properties (members) and class B is derived from
class B hence class B inherits the some properties from base class A
Chapter 7 :Inheritance
and class B also has its own additional
j.p.parmar properties.
4
Consider following example.

Chapter 7 :Inheritance
5
j.p.parmar
There are five types of inheritance in C++ listed below:
1. single level inheritance
2. multilevel inheritance
3. multiple inheritance
4. hierarchical inheritance
5. hybrid inheritance
single level inheritance :
In a single level, only single new class is derived from base class.
In the following figure, new class B is derived from base class A.

Chapter 7 :Inheritance
6
j.p.parmar
Multi level inheritance:
In a multi level, there is more than one level of derived class. In the
following figure,
class C is derived from class B and class B is derived from class A.

Chapter 7 :Inheritance
7
j.p.parmar
Multiple inheritances :
A new class is derived from more than one base class. In the
following figure, class C is derived from two based class A and B.

Chapter 7 :Inheritance
8
j.p.parmar
Hierarchical inheritance:
Here, more than one class is derived from single base class. In the
following figure, class B,C and D are derived from base class A.

Chapter 7 :Inheritance
9
j.p.parmar
Hybrid inheritance:
It is a mixing of various inheritances.

Chapter 7 :Inheritance
10
j.p.parmar
Defining derived classes:
A new class which is built from the existing (base) class is known as
derived class.
Derived class inherits the properties from the base class and also
adds additional properties of its own.
The syntax of the derived class is as follows:
class Deriveclassname : visibility Baseclassname
{

Body
};

Where Deriveclassname is the new class created from the


Baseclassname.
Body part contains members of the class and they are private,
protected or public.
Protected members are used when inheritance is used.
Chapter 7 :Inheritance
11
j.p.parmar
Visibility indicates the way the members of the base class are inherited
and accessed by the derived class. Visibility contains the keyword public,
private and protected.
private visibility:
A meaning of private visibility is that only pubic members of the base class
are accessible in the derived class and becomes private in the derived
class. private or protected members of the base class are not inherited by
the derived class.
public visibility:
A meaning of public visibility is that only pubic and protected members of
the base class are accessible in the derived class. private members of the
base class are not inherited in the derived class. Public and protected
members of the base class become public and protected in the derived
class.
protected visibility:
A meaning of protected visibility is that only pubic and protected members
of the base class are accessible in the derived class. public members and
protected members of base class become protected in the derived class.
Chapter 7 :Inheritance
j.p.parmarand protected m embers of the 12
base class become protected
Consider following example.
class Base
{
Members of base class
};

class Derived: private Base


{
Inherited members of class Base
Derived class own members
};
Visibility mode is private hence only public members of the class are
inherited in the derived class.
What to inherit from base class?
In principle, every member of a base class is inherited by a derived
class but with different access permission, but there are some
exceptions such as private members, constructor and destructor,
friend function, operator overloading function.
Chapter 7 :Inheritance
j.p.parmar
13
Single inheritance and making members of the base class
privately inherited by derived class
In an inheritance, members of the base class are inherited by
derived class either using private or public visibility mode. A
meaning of private visibility is that only pubic members of the base
class are accessible and becomes private in the derived class.
Private or protected members of the base class are not inherited by
the derived class.
In a single level inheritance, only one new class is created from the
base class.

Chapter 7 :Inheritance
j.p.parmar 14
Chapter 7 :Inheritance
15
j.p.parmar
Chapter 7 :Inheritance
16
j.p.parmar
Chapter 7 :Inheritance
17
j.p.parmar
Method overriding in the derived class:
• A derived class can override methods defined in its base class.
With overriding, the method in the subclass has the identical
signature (proto type) to the method in the base class and a
subclass implements its own version of a base class method.
• In the example-1, we have defined a member functions in the
both base and derived class with different name. What happen if
we give the same name to members (either data or function) in
the both the class.
• Consider base class and derived class has same functions name
i.e getdata() and display().

Chapter 7 :Inheritance
18
j.p.parmar
getdata() member function is defined in the derived class as:
void getdata()
{
getdata(); //call the derived class member function and create
//infinite loop
cout<<”Enter the marks for prog. in c & prog. in c++ subjects “;
cin>>cpp>>c;
total=cpp+c;
}
In this function, first line, getdata() will call the derived class function
instead of base class because default priority is given to derived class
when both base and derived class members have same name.. Hence
it call getdata() of the derived class again and again and goes to
infinite loop.
To resolve the name conflict in the inheritance, scope resolution
operator (::) is used.
The syntax for accessing members of base class from the derived class
is: Baseclassname :: members_name;
Chapter 7 :Inheritance
j.p.parmar
19
//To demonstrates the single level inheritance with private visibility
#include<iostream.h>
class Student
{
private : //private members are not inherits in the derived class
int rollno;
char name[10];
public :
void getdata()
{
cout<<endl<<”Enter rollno and name of the student “;
cin>>rollno>>name;
}
void display()
{
cout<<rollno<<” “<<name;
}
};
Chapter 7 :Inheritance
20
j.p.parmar
//derived a class Marks with privately inherited members of the base class by
//derived class using private visibility
class Marks: private Student
{ private :
int cpp, c, total;
public :
void getdata()
{
//call base class member Function using:: operator
Student :: getdata();
cout<<”Enter the marks for prog. in c & prog. in c++ subjects “;
cin>>cpp>>c;
total=cpp+c;
}
void display()
{
//call base class member Function using :: operator
Student :: display();
cout<<endl<<”cpp= “<<cpp<<” c=”<<c;
cout<<endl<<”total= “<<total;
} Chapter 7 :Inheritance
21
}; j.p.parmar
void main()
{
Marks IT3;
IT3.getdata();
IT3.display();
}

• making members of the base class publicly


inherited by derived class
• In an inheritance, members of the base class are inherited by
derived class using private, public or protected visibility mode. A
meaning of public visibility is that pubic members of the base
class are accessible and becomes public members in the derived
class and protected members of the base class are accessible
and becomes private members in the derived class.

Chapter 7 :Inheritance
22
j.p.parmar
//To inherits the base class members publicly by derived class.
#include<iostream.h>
class Student
{
protected :
int rollno;
char name[10];
public :
Student()
{
cout<<endl<<”Enter rollno and name of the student “;
cin>>rollno>>name;
}
void print()
{
cout<<”display using base class function “;
cout<<endl<<rollno<<” “<<name<<endl;
}
};
Chapter 7 :Inheritance
23
j.p.parmar
//publicly inherited base class members by derived class
//protected data members rollno, name inherited and become as private
members //of derived class
class Marks : public Student
{
private :
int cpp ,c ,total;
public :
Marks() //base class constructor is called fist, then after derived
//class constructor is called.
{
cout<<endl<<”Enter marks for prog. in c++ and prog. in c subjects“;
cin>>cpp>>c;
total=cpp + c;
}
void display()
{
cout<<rollno<<” “<<name;
cout<<endl<<”cpp=”<< cpp<<“ c= “<<c;
cout<<endl<<”total= “<<total;
} Chapter 7 :Inheritance
24
}; j.p.parmar
void main()
{
Marks IT;
IT.print();
IT.display();
}

Excercises:
• Create a base class employee with data members:
empno,name,post and appropriate member functions. Create a
derived class salary from employee with data members: basic,
HRA, DA, PF , Net_salary and appropriate member functions.
Then apply private and public visibility to it.

Chapter 7 :Inheritance
25
j.p.parmar
making members of the base class protected inherited by derived class
In an inheritance, members of the base class are inherited by derived class using
private, public or protected visibility mode. A meaning of protected visibility is
that pubic and protected members of the base class are accessible and becomes
protected members in the derived class.
//To inherits the base class members publicly by derived class.
#include<iostream.h>
class Student
{ private: int rollno;
protected :
char name[10];
public :
void getdata()
{
cout<<endl<<”Enter rollno and name of the student “;
cin>>rollno>>name;
}
void print()
{
cout<<endl<<rollno;
} Chapter 7 :Inheritance
26
}; j.p.parmar
//protected data members rollno, name and getdata(), print() functions
//inherited and become as protected members in the derived class
class Marks : protected Student
{
private :
int cpp ,c ,total;
public :
Marks()
{ getdata();
cout<<endl<<”Enter marks for prog. in c++ and prog. in c subjects“;
cin>>cpp>>c;
total=cpp + c;
}
void display()
{
print();
cout<<” “<<name;
cout<<endl<<”cpp=”<< cpp<<“ c= “<<c;
cout<<endl<<”total= “<<total;
}
}; Chapter 7 :Inheritance
27
j.p.parmar
void main()
{
Marks IT;
// following two lines is illegal for print() is a protected members of derived
// class, which makes it inaccessible outside the class.
//IT.getdata();
//IT.print();
IT.display();
}

Chapter 7 :Inheritance
28
j.p.parmar
//same program but written Student class in the separate cpp file
//To inherits the base class members publicly by derived class.
#include<iostream.h>
class Student
{
protected :
int rollno;
char name[10];
public :
Student()
{
cout<<endl<<"Enter rollno and name of the student ";
cin>>rollno>>name;
}
void print()
{
cout<<"display using base class function ";
cout<<endl<<rollno<<" "<<name<<endl;
}

};
Chapter 7 :Inheritance
29
j.p.parmar
#include<iostream.h>
#include "e:/books/cpp/student.cpp"
//publicly inherited base class members by derived class
//protected data members rollno, name inherited and become as private members of derived class
class Marks : public Student
{ private :
int cpp ,c ,total;
public :
Marks() //base class constructor is called fist, then after derived class
//constructor is called.
{
cout<<endl<<"Enter marks for prog. in c++ and prog. in c subjects";
cin>>cpp>>c;
total=cpp + c;
}
void display()
{ cout<<rollno<<" "<<name;
cout<<endl<<"cpp="<< cpp<<" c= "<<c;
cout<<endl<<"total= "<<total;
}
};
void main()
{ Marks IT;
IT.print();
IT.display();
}
//single level inheritance : Shape as base and Rectangle as derived class
#include<iostream.h>
class Shape
{
protected:
int width;
int height;
public:
void setdata(int w,int h)
{
width = w;
height=h;
}
};
// Derived class
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};

int main(void)
{
Rectangle Rect;
Rect.setdata(5,8);
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
return 0;
}
Multilevel inheritance:
In a multilevel inheritance, more than one class is derived. It contains at least two
level.
It is declared as:
Class A
{
…..
….
}
Class B : visibility mode A
{
…….
…….
}
Class C : visibility mode B
{
……
……
}
Visibility mode is private, public or protected.
Chapter 7 :Inheritance
32
j.p.parmar
//To demonstrates multi level inheritance
#include<iostream.h>
class Base
{
private: int a;
protected : int b;
public :
Base()
{
a=1;
b=2;
}
void display()
{
cout<<endl<<” a= “<<a;
}
Chapter 7 :Inheritance
}; j.p.parmar
33
//protected member data b, remain protected and display ()
//function remain public in the derived class, Derived1.
class Derived1 : public Base
{
private: int c;
protected: int d;
public:
Derived1()
{
c=3;
d=4;
}
void display()
{ Base :: display(); //call base class function
cout<<endl<<”c= “<<c;
}
Chapter 7 :Inheritance
}; j.p.parmar
34
//protected member data b, and display () function, which are now a //members
of derived class, Derived1 become private in the derived class, Derived2.
class Derived2 : private Derived1
{
private : int e;
public:
Derived2()
{
e=5;
}
void display()
{
//base::display();
Derived1 :: display();
cout<<endl<<”b= “<<b<<” d= “<<d<< “ e= “<<e;
}
};
void main()
{ Derived2 d;
d.display();
} Chapter 7 :Inheritance
35
j.p.parmar
Multiple Inheritances:
In a multiple inheritance, a new class is derived from more than one
base class. In the following figure, class C is derived from two based
class A and B.
The syntax for the derived class in a multilevel inheritance is as
follow:
Class Derived class-name : visibility base-class-1, visibility base-
class-2
{
Body
};

Chapter 7 :Inheritance
36
j.p.parmar
//an example of multiple inheritances
#include <iostream.h>
class Base1
{
protected:
int x;
public:
void show_x()
{
cout<<"x= "<<x<<endl;
}
};
class Base2
{
protected:
int y;
public:
void show_y()
{
cout <<"y= "<<y<<endl;
} Chapter 7 :Inheritance
37
}; j.p.parmar
// inherit multiple base classes, Base1 and Base2
//members from both the class , Base1 and Base2 are accessible in Derived
class.
class Derived: public Base1, public Base2
{
public:
void set(int i, int j)
{
x = i; y = j;
}
};

void main()
{
Derived obj;
obj.set(5, 10);
obj.show_x(); // call from base1
obj.show_y(); // call from base2
}
Chapter 7 :Inheritance
38
j.p.parmar
//example of multiple inheritance: from Shape and paintcost a new class Rectangle is derived.
#include <iostream.h>
// Base class Shape
class Shape
{
protected:
int width;
int height;
public:
void setdata(int w,int h)
{
width = w;
height=h;
}
};
// Base class PaintCost
class PaintCost
{
protected:
int cost;
public:
void getdata()
{
cout<<"enter cost of painting of rectagle:";
cin>>cost;
}
int getCost(int area)
{
return area * cost;
}
};
// Derived class
class Rectangle: public Shape, public PaintCost
{
public:
int getArea()
{
return (width * height);
}
};

int main(void)
{
Rectangle Rect;
//PaintCost p;
int area;
Rect.setdata(5,9);
area = Rect.getArea();
// Print the area of the object.
cout << "Total area: " << Rect.getArea() << endl;
Rect.getdata();
// Print the total cost of painting
cout << "Total paint cost:Rs " << Rect.getCost(area) << endl;
return 0;
One more example of multiple inheritance

//example of multiple inheritances


//calculate area and perimeter of a rectangle
#include<iostream.h>
class area
{
public:
float area_calculate(float l,float b)
{
return l*b;
}
};

class perimeter
{
public:
float peri_calculate(float l,float b)
{
return 2*(l+b);
}
};
class rectangle : private area, private perimeter
{
private:
float length,breadth;
public:
rectangle()
{
cout<<"\nenter length:";
cin>>length;
cout<<"\nenter breadth:";
cin>>breadth;
}
float area_calculate()
{
float a;
a= area::area_calculate( length, breadth);
return a;
}
float peri_calculate()
{
float p;
p=perimeter::peri_calculate( length, breadth);
return p;
}
};
void main()
{
rectangle r;
cout<<"\n area of a rectangle:"<<r.area_calculate()<<" square meter";
cout<<"\n perimeter of a rectangle:"<<r.peri_calculate()<<" meter";
}
Advantage of multiple inheritances:
1. It provides greater degree of flexibility and simplicity, thus it is
easier to define small and simple classes.
2. It clearly favors the reusability.
3. It is easier to change the implementation of a class while leaving
its interface untouched.

Chapter 7 :Inheritance
43
j.p.parmar
Hierarchical Inheritance:
Example

Chapter 7 :Inheritance
44
j.p.parmar
Chapter 7 :Inheritance
45
j.p.parmar
class Commission : public Hours
{
private :
float commiss, totalsale;
public :
Commission()
{
commiss=7.5;
totalsale=1000;
}
float calculate_pay()
{
float pay;
pay= Hours::calculate_pay() + ((commiss * totalsale)/100);
cout<<empname;
return pay;
}
}; Chapter 7 :Inheritance
46
j.p.parmar
class Weeks : public Salary
{
private :float weekrate;
public :
Weeks()
{
weekrate=1000;
}
float calculate_pay()
{
cout<<empname;
return weekrate;
}
};
void main()
{
Commission emp1;
cout<<"hourly base salary for the employee ";
cout<<" is "<<emp1.Hours::calculate_pay();
cout<<endl<<"hourly base salary with commission for the employee ";
cout<<" is "<<emp1.Commission::calculate_pay();
Weeks emp2;
cout<<endl<<"week base salary of a employee ";
Chapter 7 :Inheritance
cout<<" is "<<emp2.Weeks::calculate_pay(); 47
j.p.parmar
}
Hierarchical Inheritance:
In a hierarchical inheritance, more than one class is derived from
single base class. In the following figure, class B, C and D are derived
from base class A.

Chapter 7 :Inheritance
48
j.p.parmar
//example of hierachical inheriance : Rectangle and Triangle are derived from Shape class
#include <iostream.h>
class Shape
{
protected:
int width, height;
};

class Rectangle: public Shape


{
public:
Rectangle(int a, int b)
{
width=a;
height=b;
}
int area()
{
cout<<endl<<"Rectangle class area :" ;
return (width * height);
}
};
class Triangle: public Shape
{
public:
Triangle(int a, int b)
{
width=a;
height=b;
}
int area()
{
cout<<endl<<"Triangle class area :";
return (width * height / 2);
}
};

int main( )
{
Rectangle rec(10,7);
Triangle tri(10,5);
// call rectangle area.
cout<<rec.area()<<endl;
// call triangle area.
cout<<tri.area()<<endl;
return 0;
}
Exercise :
• From the base class, rectangle derived a two
new classes area and perimeter.
Hybrid Inheritance, Virtual Base classes and abstract class
It is a mixing of more than one type of inheritance.
Consider following example.

In the above example, all three type of inheritance, multilevel,


multiple and hierarchical inheritance exist. Grandchild derived class
has two base classes, Child1 and Child2.
Grandchild inherits members ofChapter
Parent class via two separate paths.
7 :Inheritance
52
Hence Parent base class is also known
j.p.parmaras indirect base class..
This inheritance creates problems because public and protected
members of the Parent class are inherited by Grandchild two times
via Child1 and Child2. Because of this duplication, ambiguity occurs.
To avoid this ambiguity, a common base class Parent is declared as
virtual base class. Hence only one copy of members of Parent class is
inherited by Grandchild class.
class Derived class name :virtual public base class name
{
Body
}
virtual and public keywords may be used in either order.

Chapter 7 :Inheritance
53
j.p.parmar
//an example of hybrid inheritance
#include<iostream.h>
class Parent
{
public:
int data;
Parent()
{
data=15;
}
};

class Child2:virtual public Parent


{
public:
int data2;
Child2()
{
data=25;
data2=10;
} Chapter 7 :Inheritance
54
}; j.p.parmar
class Child1:public virtual Parent
{ public :
int data1;
Child1()
{
data=20;
data1=5;
}

};
class Grandchild:public Child1,public Child2
{
public:
Grandchild()
{ }
void display()
{
cout<<endl<<"data= "<<data<<endl;
cout<<" data1= "<<data1<<endl;
cout<<" data2="<<data2<<endl;
} Chapter 7 :Inheritance
55
}; j.p.parmar
void main()
{
Grandchild gc;
gc.display();
}

Abstract Classes:
An abstract class is a class which is not used to create objects but
work as a base class only so from this base class, other classes may
be developed. In the previous examples, Parent class or Salary class
are the abstract classes.

Chapter 7 :Inheritance
56
j.p.parmar
Constructor in Derived Classes
• To initialize data members, constructor function is used. it is best practice to use constructor
function in the base as well as in the derived class. But in the inheritance, we create an object
of derived class only. When object of derived class is created, derived class constructor is
called but how does we call base class constructor?
• Constructor without arguments (default constructors) and destructors in both the base and
derived class are called automatically when object of derived class is created and destroyed.
• When constructors have arguments , then base class constructor is called from the derived
class constructor definition using following syntax:
Derived class constructor name(arguments list): base class constructor name(arguments list)
{
Body
}
Here, Arguments list of derived class constructor includes the arguments of derived class
constructor plus base class constructor arguments.
//To demonstrates single level inheritance with constructor functions
//calling base class constructor from the derived class
#include<iostream.h>
#include<string.h>
class Student
{
private :
int rollno;
char name[20];
public :
Student(int r,char *s)
{
rollno = r;
strcpy(name, s);
}
void display()
{
cout<<rollno<<” “<<name;
}
};

Chapter 7 :Inheritance
58
j.p.parmar
class Marks : private Student //private visibility mode
{
private :
int cpp, c, total;
public :
// call base class constructor with two arguments passed by derived class //constructor
Marks(int r, char *s, int c, int cpp) : student(r, s)
{
this->c=c;
this->cpp =c pp;
total=cpp + c;
}
void display()
{
Student::display();
cout<<endl<<”cpp= “<<cpp<<” c=”<<c;
cout<<endl<<”total= “<<total;
}
};
void main()
{
Marks IT3 (22, "kaushalay", 66 , 77);
IT3.display();
} Chapter 7 :Inheritance
59
j.p.parmar
//example of hierarchical inheritance : Rectangle and Triangle are derived from Shape class
//inhe-hir.cpp
#include <iostream.h>
class Shape
{
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
};

class Rectangle: public Shape


{
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area ()
{
cout<<endl<<"Rectangle class area :" ;
return (width * height);
}
};
Chapter 7 :Inheritance
60
j.p.parmar
class Triangle: public Shape
{
public:
Triangle(int a, int b)
{
width=a;
height=b;
}
int area()
{
cout<<endl<<"Triangle class area :";
return (width * height / 2);
}
};

int main( )
{
Rectangle rec(10,7);
Triangle tri(10,5);
// call rectangle area.
cout<<rec.area()<<endl;
// call triangle area.
cout<<tri.area()<<endl;
return 0;
}
Chapter 7 :Inheritance
61
j.p.parmar
Question bank

Define inheritance.
Explain in brief types of inheritance with example.
[GTU exam april 2010, jan 2010]
Explain various visibility modes with example.
What is inheritance? How multilevel and multiple inheritance differ ?
Explain with example. [GTU exam may2011]
What is method overriding?
What is virtual base class?
Write a program using multiple inheritances.
Write a program using hierarchical inheritance.
Write program to prepare mark-sheet for diploma engg students, create
class student as base class and TW and EXT as derived class from it, result
class is derived from these two classes TW and EXT. [GTU exam april
2010]

Chapter 7 :Inheritance
62
j.p.parmar

You might also like