Skip to content

Hierarchical inheritance

๐Ÿ“˜ 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 and ScienceTeacher inherit the method displaySubject() from the base class Teacher.
  • 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:

ClassInherits FromMethods Inherited
Teacher (Base)โ€”displaySubject()
MathTeacherTeacherdisplaySubject(), teachMath()
ScienceTeacherTeacherdisplaySubject(), teachScience()