Virtual Base Class

  •  A virtual base class is used to solve a problem like diamond shape problem.

Diamond shape problem



// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;


class A{
    public:
    void showA(){
        cout<<"Class A";
    }
};

class B:public A{
    public:
    void showB(){
        cout<<"Class B";
    }
};

class C:public A{
    public:
    void showC(){
        cout<<"Class A";
    }
};

class D:public B,public C{
    public:
    void showD(){
        cout<<"Class B";
    }
};


int main() {
  D d;
 
  d.showA();
  d.showB();
  d.showC();
  d.showD();
    return 0;
}

  • This program will give error like this : error: request for member 'showA' is ambiguous .
  • This error appears because to execute method show a there are two ways i.e from class B or from class C, so the compiler will be confused that which one to execute because for compiler there are two showA method and it is ambiguous for it so, it throws an error.
  • To solve this error, class A is inherited in class C and class B virtually due to which it makes single way for showA function.

Solution of Ambiguity or Diamond shape problem using virtual base class:




// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;


class A{
    public:
    void showA(){
        cout<<"Class A"<<endl;
    }
};

class B: virtual public A{
    public:
    void showB(){
        cout<<"Class B"<<endl;
    }
};

class C: virtual public A{
    public:
     void showC(){
        cout<<"Class A"<<endl;
    }
};

class D:public B,public C{
    public:
    void showD(){
        cout<<"Class B"<<endl;
    }
};


int main() {
  D d;
 
  d.showA();
  d.showB();
  d.showC();
  d.showD();
    return 0;
}

//output
//class A
//class B
//class C
//class D


Post a Comment

Previous Post Next Post