Hybrid-Inheritance-in-C++ .

In this session i have discussed hybrid inheritance in C++ .


Hybrid inheritance is the combine more than one inheritance . It includes single , multiple , hierarchical , multilevel inheritance .


hybrid inheritance image

In above image we combine the two inheritance hierarchical and multiple inheritance . The B and C class inherit from A class it shows the hierarchical inheritance . The B and C class inherit in D class that means multiple inheritance occure .

Hybrid Inheritance Demo :

Example : Write a program that demonstrate the hybrid inheritance in C++

    #include<iostream>
    using namespace std;  
    class A
    {
        public :
        void sum(int x,int y)
        {
            int result = x + y;
            cout<<"\nSum : "<<result;
        }
    };
    class B : public A
    {
        public :
        void sub(int x,int y)
        {
            int result = x - y;
            cout<<"\nSub : "<<result;
        }
    };
    class C : public A
    { 
        public :
        void mul(int x,int y)
        {
            int result = x * y;
            cout<<"\nMulti : "<<result;
        }
    };
    class D : public B , public C
    { 
        public :
        void div(int x,int y)
        {
            int result = x / y;
            cout<<"\nDiv : "<<result;
        }
    };
   
    int main()
    {
            B obj1;
            obj1.sum(20,10);
            D obj2;
            obj2.sub(20, 10);
            obj2.mul(20, 10);
            obj2.div(20, 10);
            return 0;
    }
    OUTPUT : Sum  : 30
             Sub  : 10
             Multi: 200
             Div  : 2  
    

In the above program if you call the sum with object of D class it will produce a error for sum() as ambiguous . It is the draw back of hybrid inheritance . It will discuss later in details in virtual topic.

Welcome to AndroidATPoint.

back image                     next image