Multilevel inheritance in C++
Overview
Multilevel inheritance in C++ is a scenario whereby a class is derived from a particular class, which is already derived from another class.
Note: To understand inheritance in C++ click on this shot.
The figure below shows the visual representation of multilevel inheritance in C++:
Example
In the code below, we derive a class son from another class father which is derived from a parent class grandfather :
#include <iostream>using namespace std;// creating a parent classclass Grandfather{ // this is the parent classpublic: // this is the access specifiervoid myfunction() {cout<<"Gramdfather is the parent class. \nFather is derived from the Grandfather. \nAnd Son is derived from Father.";}};// deriving a class from the parent classclass Father: public Grandfather {};// deriving anogther class from the derived class aboveclass Son: public Father {};int main(){Son myobject; // this is an object of the classmyobject.myfunction(); // calling the functionreturn 0;}
Explanation
- Line 6: We create a parent class
Grandfather. - Line 7: We make the member or attribute of the class public by using the
publickeyword. - Line 8: We create a function for the
myfunctionclass. - Line 9: We create a block of code to execute when we call the
myfunctionfunction. - Line 14: We derive a class
Fatherfrom the parent classGrandfather. - Line 18: We derive another class
Sonfrom the derived classFather. - Line 22: We create an object (
myobject)of the class (Son).
- Line 23: We call the function
(myfunction).