Summary: In this tutorial, we will learn what hybrid inheritance is and how can we implement hybrid inheritance in C++.

Introduction to Hybrid Inheritance

Inheritance is the reusability of the code by inheriting or extending one class to another.

When more than one type of inheritance is involved in the program, we call it hybrid inheritance.

In short, hybrid inheritance is a combination of two or more types of inheritance.

For example, implementing single and multilevel inheritances in the same program.

Examples of Hybrid Inheritance using Block Diagram

Example 1: Single + Multiple Inheritance

Hybrid inheritance example 3

Each block in this diagram represents a class and the corresponding arrow the inheritance of a class.

In this block example, we have implemented single and multiple inheritances.

Example 2: Single + Multilevel Inheritance

Hybrid inheritance example 2

We can also implement other types of inheritance to constitute hybrid inheritance.

C++ Example: Hybrid Inheritance

#include <iostream>
using namespace std;
 
class Animal{
public:
    Animal(){
        cout << "This is an Animal ";
    }
};

//single inheritance 
class Dog: public Animal{
public:
    Dog(){
        cout << "that is Dog ";
    }
};
 
class Domestic{
public:
    Domestic(){
        cout << "and Domestic";
    }
};

//Multiple Inheritance 
class Rocky: public Dog, public Domestic{
public:
    Rocky(){
        cout << "\nName of the dog is Rocky! \n";
    }
};
 
int main()
{
    Rocky mydog;
    return 0;
}

Output:

This is an Animal that is Dog and Domestic
Name of the dog is Rocky!

Recommended Read: Diamond Problem in Inheritance

In this programming tutorial, we learned about hybrid inheritance in C++ with the help of examples.

Leave a Reply