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++:

Visual representation of multi-level inheritance

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 class
class Grandfather{ // this is the parent class
public: // this is the access specifier
void 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 class
class Father: public Grandfather {
};
// deriving anogther class from the derived class above
class Son: public Father {
};
int main(){
Son myobject; // this is an object of the class
myobject.myfunction(); // calling the function
return 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 public keyword.
  • Line 8: We create a function for the myfunction class.
  • Line 9: We create a block of code to execute when we call the myfunction function.
  • Line 14: We derive a class Father from the parent class Grandfather.
  • Line 18: We derive another class Son from the derived class Father.
  • Line 22: We create an object (myobject)of the class (Son).
  • Line 23: We call the function (myfunction).

Free Resources