C++ Inheritance - 4
C++ Inheritance - 4
C++ Tutorials
If a class is derived from another derived class then it is called multilevel inheritance. So in C++ multilevel
inheritance, a class has more than one parent class.
For example, if we take animals as a base class then mammals are the derived class which has features of
animals and then humans are the also derived class that is derived from sub-class mammals which inherit all
the features of mammals.
www.trytoprogram.com/cplusplus-programming/multilevel-inheritance/ 1/5
10/13/2020 C++ Multilevel Inheritance (With Examples) - Trytoprogram
As shown in above block diagram, class C has class B and class A as parent classes. Depending on the relation
the level of inheritance can be extended to any level.
As in other inheritance, based on the visibility mode used or access speci er used while deriving, the
properties of the base class are derived. Access speci er can be private, protected or public.
Click here to learn in detail about access speci ers and their use in inheritance
www.trytoprogram.com/cplusplus-programming/multilevel-inheritance/ 2/5
10/13/2020 C++ Multilevel Inheritance (With Examples) - Trytoprogram
www.trytoprogram.com/cplusplus-programming/multilevel-inheritance/ 3/5
10/13/2020 C++ Multilevel Inheritance (With Examples) - Trytoprogram
// inheritance.cpp
#include <iostream>
using namespace std;
class base //single base class
{
public:
int x;
void getdata()
{
cout << "Enter value of x= "; cin >> x;
}
};
class derive1 : public base // derived class from base class
{
public:
int y;
void readdata()
{
cout << "\nEnter value of y= "; cin >> y;
}
};
class derive2 : public derive1 // derived from class derive1
{
private:
int z;
public:
void indata()
{
cout << "\nEnter value of z= "; cin >> z;
}
void product()
{
cout << "\nProduct= " << x * y * z;
}
};
int main()
{
derive2 a; //object of derived class
a.getdata();
a.readdata();
a.indata();
www.trytoprogram.com/cplusplus-programming/multilevel-inheritance/ 4/5
10/13/2020 C++ Multilevel Inheritance (With Examples) - Trytoprogram
a.product();
return 0;
} //end of program
Output
Enter value of x= 2
Enter value of y= 3
Enter value of z= 3
Product= 18
www.trytoprogram.com/cplusplus-programming/multilevel-inheritance/ 5/5