Hybrid Inheritance

ho-ssain's avatar
Published Feb 18, 2025
Contribute to Docs

Hybrid inheritance is an object-oriented programming (OOP) concept where a class can inherit methods and properties from multiple base classes, forming a complex class hierarchy. This allows for the combination of multiple inheritance types, such as single, multiple, and multilevel inheritance.

Syntax

In C++, hybrid inheritance follows this syntax:

class BaseClass1 {
  // Base class 1 members
};

class BaseClass2 {
  // Base class 2 members
};

class DerivedClass : AccessSpecifier BaseClass1, AccessSpecifier BaseClass2 {
  // Derived class members
};

Example

In the following example, hybrid inheritance is demonstrated where Child inherits from both Parent1 and Parent2, allowing Child to access methods from both the base classes:

#include <iostream>
using namespace std;
class Parent1 {
public:
void method1() {
cout << "Method from Parent1." << endl;
}
};
class Parent2 {
public:
void method2() {
cout << "Method from Parent2." << endl;
}
};
class Child : public Parent1, public Parent2 {
public:
void method3() {
cout << "Method from Child." << endl;
}
};
int main() {
Child myChild;
myChild.method1(); // Inherited from Parent1
myChild.method2(); // Inherited from Parent2
myChild.method3(); // Defined in Child
return 0;
}

The output of the above code will be:

Method from Parent1.
Method from Parent2.
Method from Child.

Codebyte Example

The following codebyte example demonstrates how hybrid inheritance enables a class to inherit methods and properties from multiple base classes, forming a complex class hierarchy:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy