Skip to content

Hybrid inheritance

๐Ÿ“˜ What is Hybrid Inheritance?

Hybrid Inheritance is a combination of two or more types of inheritance (e.g., single, multiple, multilevel, hierarchical) in a single program.

It often arises when designing complex systems where different classes share relationships in multiple ways.


๐Ÿง  Real-Life Analogy

Imagine:

  • A Person is a base class.
  • Teacher and Researcher both inherit from Person.
  • A class Professor inherits from both Teacher and Researcher.

This forms a combination of hierarchical and multiple inheritance โ†’ this is Hybrid Inheritance.


๐Ÿ”ท Structure Example:

      Person
/ \
Teacher Researcher
\ /
Professor

Here, the Professor inherits from both Teacher and Researcher, which in turn inherit from the common base class Person.


โš ๏ธ Problem: Diamond Problem

In hybrid inheritance, if two parent classes inherit from the same base class, and then a class inherits from both of them, ambiguity arises.

This is called the diamond problem.

๐Ÿ’ก Solution: Use virtual inheritance to avoid duplication of base class members.


๐Ÿงช C++ Example of Hybrid Inheritance with Virtual Base Class

#include <iostream>
using namespace std;

// Base Class
class Person {
public:
void showPerson() {
cout << "Person: General Information." << endl;
}
};

// First Derived Class (virtually inherits Person)
class Teacher : virtual public Person {
public:
void showTeacher() {
cout << "Teacher: Teaches students." << endl;
}
};

// Second Derived Class (virtually inherits Person)
class Researcher : virtual public Person {
public:
void showResearcher() {
cout << "Researcher: Conducts research." << endl;
}
};

// Final Derived Class (inherits from both Teacher and Researcher)
class Professor : public Teacher, public Researcher {
public:
void showProfessor() {
cout << "Professor: Teaches and conducts research." << endl;
}
};

int main() {
Professor p;
p.showPerson(); // From Person class
p.showTeacher(); // From Teacher class
p.showResearcher(); // From Researcher class
p.showProfessor(); // Own method
return 0;
}

โœ… Output:

Person: General Information.
Teacher: Teaches students.
Researcher: Conducts research.
Professor: Teaches and conducts research.

๐ŸŽฏ Key Concepts:

  • Teacher and Researcher virtually inherit from Person.
  • Professor inherits from both Teacher and Researcher.
  • Virtual inheritance ensures only one copy of Person exists in Professor.

โœ… Advantages:

  • Combines power of multiple inheritance types.
  • Ideal for designing complex systems.
  • Encourages code reusability and clear structure.

โŒ Disadvantages:

  • Can be confusing if not designed carefully.
  • Without virtual inheritance, leads to ambiguity (diamond problem).

๐Ÿ“Œ Summary Table:

ClassInherits FromNotes
Personโ€”Base class
Teachervirtual public PersonHierarchical inheritance
Researchervirtual public PersonHierarchical inheritance
ProfessorTeacher, ResearcherMultiple + Hierarchical = Hybrid