Hybrid Inheritance in C++

In "Hybrid Inheritance" we use more than one type of Inheritance at once. It is also known as "Multipath Inheritance".

Hybrid Inheritance

Basically it is the hybrid of different type of inheritances like "Single Inheritance", "Multiple Inheritance", "Multilevel Inheritance", "Hierarchical Inheritance"We can use any combination as per the requirements. Here we are going to use the most common combination in the Hybrid Inheritance i.e, Hierarchical Inheritance + Multiple Inheritance to understand it. 

Block-Diagram
Block Diagram


Syntax:-
class Parent
{
//Body of the Parent class
};
class Child1 : access_specifier Parent
{
//Body of the Child1 class
};
class Child2 : access_specifier Parent
{
//Body of the Child2 class
};
class Child3 : access_specifier Child1, access_specifier Child2
{
//Body of the Child3 class
};

 

Example of Hybrid Inheritance
#include<iostream>
using namespace std;

class Parent
{
 protected:
  int a=10;
};
class Child1:virtual public Parent
{
//We use "virtual" keyword to avoid Ambiguity.
 protected:
  int b=8;
  int G_ab;
 public:
  void Greater_ab(){
   if(a>b) G_ab=a;
   else G_ab=b;
  }
};
class Child2:virtual public Parent
{
 protected: 
  int c=12;
  int G_ac;
 public:
  void Greater_ac(){
   if(a>c) G_ac=a;
   else G_ac=c;
  }
};class Child : public Child1, public Child2
{
 protected:
  int G;
 public:
  void Greater()
  {
   if(G_ab>G_ac) G=G_ab;
   else G=G_ac;
   cout<<"The Greatest Number is "<<G;
  }
};

int main() { Child x; //'x' is the object of "Child class" x.Greater_ab(); x.Greater_ac(); x.Greater(); }
Hierarchical Inheritance

For giving some suggestion please comment us or check our "Contact us" page. Also more update related to coding will be added in this Blog later on, so please get attached with this Blog by clicking the follow button. Thank you for your support and time... 

Post a Comment

0 Comments