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.
Here is the block diagram of C++ multilevel inheritance to make it clear.
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 specifier used while deriving, the properties of the base class are derived. Access specifier can be private, protected or public.
Click here to learn in detail about access specifiers and their use in inheritance
class A // base class
{
...........
};
class B : acess_specifier A // derived class
{
...........
} ;
class C : access_specifier B // derived from derived class B
{
...........
} ;
Here is a simple example to illustrate the concept of c++ multilevel inheritance.
[adsense1]
// 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();
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