Virtual-Base-Class-in-C++ .

In this session i have discussed virtual base class in C++ .


In hybrid inheritance we saw that if we call sum() with object of D class on that case it will produces the error sum() as ambiguous . You can solve this proble by using virtual base class .


Virtual Base Class Demo :

Example : Write a program that demonstrate the use of virtual base class 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 : virtual public A
    {
        public :
        void sub(int x,int y)
        {
            int result = x - y;
            cout<<"\nSub : "<<result;
        }
    };
    class C : virtual 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()
    {
            D obj;
            obj.sum(20,10);
            obj.sub(20, 10);
            obj.mul(20, 10);
            obj.div(20, 10);
            return 0;
    }
    OUTPUT : Sum  : 30
             Sub  : 10
             Multi: 200
             Div  : 2  
    

Welcome to AndroidATPoint.

back image                     next image