• Home
  • What is Hybrid Inheritance in C++ : Syntax, Examples

What is Hybrid Inheritance in C++ : Syntax, Examples

Hybrid Inheritance in C++ is a combination of two or more types of inheritance, such as single inheritance, multiple inheritance, and multilevel inheritance. It is a way of defining a new class that is derived from more than one base class.

Here is an example of hybrid inheritance in C++:

#include <iostream>
using namespace std;

// Base class 1
class A {
public:
int a;
void get_a() {
cout << "Enter value of a: ";
cin >> a;
}
};

// Base class 2
class B {
public:
int b;
void get_b() {
cout << "Enter value of b: ";
cin >> b;
}
};

// Derived class 1
class C: public A {
public:
int c;
void get_c() {
cout << "Enter value of c: ";
cin >> c;
}
};

// Derived class 2
class D: public B {
public:
int d;
void get_d() {
cout << "Enter value of d: ";
cin >> d;
}
};

// Hybrid derived class
class E: public C, public D {
public:
int e;
void get_e() {
cout << "Enter value of e: ";
cin >> e;
}
void display() {
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
cout << "d = " << d << endl;
cout << "e = " << e << endl;
}
};

int main() {
E obj;
obj.get_a();
obj.get_b();
obj.get_c();
obj.get_d();
obj.get_e();
obj.display();
return 0;
}

In this example, class A and B are the base classes, and class C and D are derived classes. Class E is a hybrid derived class that is derived from both class C and class D, which are derived from base classes A and B, respectively.