Skip to content

Multilevel inheritance

๐Ÿ“˜ What is Multilevel Inheritance?

Multilevel Inheritance is a type of inheritance where a class is derived from a derived class.

It forms a chain of inheritance, like this:

Base โ†’ Intermediate โ†’ Derived

Each derived class inherits features from its immediate base class, and ultimately from the original base class.


๐Ÿง  Real-Life Analogy

Imagine:

  • A Grandfather passes knowledge to the Father.
  • The Father passes it to the Son.

This chain of inheritance is like multilevel inheritance.


๐Ÿ”ง Syntax:

class A {
// Base class
};

class B : public A {
// Derived from A
};

class C : public B {
// Derived from B (indirectly inherits from A too)
};

๐Ÿงช C++ Program: Multilevel Inheritance

#include <iostream>
using namespace std;

// Base class
class Grandfather {
public:
void displayGrandfather() {
cout << "Grandfather: Wisdom and experience." << endl;
}
};

// Intermediate class
class Father : public Grandfather {
public:
void displayFather() {
cout << "Father: Hardworking and responsible." << endl;
}
};

// Derived class
class Son : public Father {
public:
void displaySon() {
cout << "Son: Energetic and ambitious." << endl;
}
};

int main() {
Son s;
s.displayGrandfather(); // From Grandfather class
s.displayFather(); // From Father class
s.displaySon(); // Own method
return 0;
}

โœ… Output:

Grandfather: Wisdom and experience.  
Father: Hardworking and responsible.
Son: Energetic and ambitious.

๐Ÿ” Key Concepts:

  • Son inherits from Father, and Father inherits from Grandfather.
  • Son has access to all public members of Father and Grandfather.
  • This is an example of Multilevel Inheritance.

โœ… Advantages:

  • Step-by-step extension of class features.
  • Code reusability across multiple levels.
  • Maintains a clear and logical hierarchy.

โŒ Disadvantages:

  • Can become complex and harder to debug in deep hierarchies.
  • Changes in a base class may affect all levels down the chain.

๐Ÿ“Œ Summary Table

ClassInherits FromContains Features Of
Grandfatherโ€”Grandfather
FatherGrandfatherFather + Grandfather
SonFatherSon + Father + Grandfather