๐ What is Hierarchical Inheritance?
Hierarchical Inheritance occurs when multiple derived classes inherit from a single base class.
๐ง Real-Life Analogy:
Imagine a Teacher class that defines common characteristics. Then, two specialized classes like MathTeacher and ScienceTeacher inherit from it.
๐งฑ Structure:
Base
/ \
Derived1 Derived2
So, each derived class gets access to the common properties of the base class, but can also define its own.
๐ง Syntax:
class Base {
// Common functionality
};
class Derived1 : public Base {
// Inherits from Base
};
class Derived2 : public Base {
// Inherits from Base
};
๐งช C++ Example Program: Hierarchical Inheritance
#include <iostream>
using namespace std;
// Base Class
class Teacher {
public:
void displaySubject() {
cout << "Teaches subjects in school." << endl;
}
};
// Derived Class 1
class MathTeacher : public Teacher {
public:
void teachMath() {
cout << "Teaches Mathematics." << endl;
}
};
// Derived Class 2
class ScienceTeacher : public Teacher {
public:
void teachScience() {
cout << "Teaches Science." << endl;
}
};
int main() {
MathTeacher m;
ScienceTeacher s;
cout << "--- Math Teacher ---" << endl;
m.displaySubject();
m.teachMath();
cout << "\n--- Science Teacher ---" << endl;
s.displaySubject();
s.teachScience();
return 0;
}
โ Output:
--- Math Teacher ---
Teaches subjects in school.
Teaches Mathematics.
--- Science Teacher ---
Teaches subjects in school.
Teaches Science.
๐ฏ Key Points:
- Both
MathTeacher
andScienceTeacher
inherit the methoddisplaySubject()
from the base classTeacher
. - Each derived class adds its own specific functionality.
- Encourages code reusability and organization.
โ Advantages of Hierarchical Inheritance:
- Shared functionality is written only once in the base class.
- Easy to extend and maintain.
- Encourages logical class structure.
โ Limitations:
- Cannot share data between sibling classes directly.
- Deep hierarchies can become hard to manage.
๐ Summary Table:
Class | Inherits From | Methods Inherited |
---|---|---|
Teacher (Base) | โ | displaySubject() |
MathTeacher | Teacher | displaySubject() , teachMath() |
ScienceTeacher | Teacher | displaySubject() , teachScience() |