Hybrid Inheritance in C++

Any combination of above three inheritance (single, hierarchical and multiple) is called as hybrid inheritance (also known as Virtual Inheritance).

Syntax:

class A

{

     //body of class A

};

class B : public A

{

     //body of class B

};

class C : public A

{

     //body of class C

};

class D : public B, public C

{

     //body of class D

};

 

Example:

#include<iostream>

using namespace std;

class A{                          // Base class     

           public:

                int x;

}; 

class B{                          //derived1 class

             public:

                int x=8;

};

class C{                         //derived2 class

            public:

               int y=5;

};

class D:public B ,public C{     //D is derived from class B and class C

            public:

               void sum(){

                               cout<< "Sum= " <<x+y;

               }

};       

int main(){

     D obj1;    //create D class obj1

     obj1.sum();

     return 0;   

}

[

Output:

 

Post a Comment

0 Comments

Close Menu