What is Hybrid Inheritance in C++

Hybrid or Multipath Inheritance in C++

On this page we will discuss about hybrid inheritance in C++ . As we know that inheritance is the process of  extending the source code of one class to another class . It’s interesting to know that we can have the combination of both multilevel and Hierarchical Inheritance . This type of inheritance is also known as Multipath or Hybrid Inheritance
hybrid inheritance in c++

Syntax to Implement Hybrid Inheritance in C++

  • The class that is acquiring the behaviors is called child class or derived class or subclass
  • The class from which behaviors are taken is called parent class or superclass or base class
class parent
{
  ----;
};
class child1: access parent
{
  -----;
  //contains properties of both
  //parent+child1
};
class child2: access parent
{
  ----;
  //contains properties of both
  //parent+child2
};
class child2_1: access child2
{
  -----;
  //contains properties of both
  //parent+child2+child2_1
};
class child1_1:access child1
{
  -----;
  //contains properties of both
  //parent+child2+child1_1
};

Example: Program to demonstrate hybrid inheritance

Run
#include <iostream>
using namespace std;
class A
{

public:
void m1()
{
cout<<"\n m1 from class A";
}

};

class B: public A//B class inherits A as Parent
{

public:
void m2()
{
cout<<"\n m2 from class B";
}
//contains data of A+B

};

class C: public A//C class inherits A as Parent
{

public:
void m3()
{
cout<<"\n m3 from class C"; } //Contains data of A+C }; class D:public B//multilevel inheritance from A->B->D 
{

public:
void m4()
{
  cout<<"\n m4 from class D"; } //contains data of class A+B+D }; class E:public C//multilevel inheritance from A->C->E
{

public:
void m5()
{
  cout<<"\n m5 from class E";
}
  //contains data of class A+C+E

};

main()
{
  D d;//contains A+B+D properties 
  d.m1();
  d.m2();
  d.m4();
  E e;//contains A+C+E properties 
  e.m1();
  e.m3();
  e.m5();

}


Output:

m1 from class A
m2 from class B
m4 from class D
m1 from class A
m3 from class C
m5 from class E

Hierarchal Inheritance from A-B and A-C

  • Class B contains 2 methods m1() from class A and m2() by its own
  • Class C contains 2 methods m1() from class A and m3() by its own

Multilevel inheritance from class A-B-D and A-C-E

  • Class D contains 3 methods m1() from class A and m2() from class B and its own method m4()
  • Class E contains 3 methods m1() from class A and m3() from class C and its own method m5()

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription