๐ 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 fromFather
, andFather
inherits fromGrandfather
.Son
has access to all public members ofFather
andGrandfather
.- 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
Class | Inherits From | Contains Features Of |
---|---|---|
Grandfather | โ | Grandfather |
Father | Grandfather | Father + Grandfather |
Son | Father | Son + Father + Grandfather |