What is a virtual base class in C++?


The virtual base class is used when a derived class has multiple copies of the base class.

Example Code

#include <iostream>
using namespace std;
class B {
   public: int b;
};

class D1 : public B {
   public: int d1;
};

class D2 : public B {
   public: int d2;
};

class D3 : public D1, public D2 {
   public: int d3;
};

int main() {
   D3 obj;

   obj.b = 40; //Statement 1, error will occur
   obj.b = 30; //statement 2, error will occur
   obj.d1 = 60;
   obj.d2 = 70;
   obj.d3 = 80;

   cout<< "\n B : "<< obj.b
   cout<< "\n D1 : "<< obj.d1;
   cout<< "\n D2: "<< obj.d2;
   cout<< "\n D3: "<< obj.d3;
}

In the above example, both D1 & D2 inherit B, they both have a single copy of B. However, D3 inherit both D1 & D2, therefore D3 have two copies of B, one from D1 and another from D2.

Statement 1 and 2 in above example will generate error, as compiler can't differentiate between two copies of b in D3.

To remove multiple copies of B from D3, we must inherit B in D1 and D3 as virtual class.

So, above example using virtual base class will be −

Example Code

 Live Demo

#include<iostream>
using namespace std;
class B {
   public: int b;
};

class D1 : virtual public B {
   public: int d1;
};

class D2 : virtual public B {
   public: int d2;
};

class D3 : public D1, public D2 {
   public: int d3;
};

int main() {
   D3 obj;

   obj.b = 40; // statement 3
   obj.b = 30; // statement 4

   obj.d1 = 60;
   obj.d2 = 70;
   obj.d3 = 80;

   cout<< "\n B : "<< obj.b;
   cout<< "\n D1 : "<< obj.d1;
   cout<< "\n D2 : "<< obj.d2;
   cout<< "\n D3 : "<< obj.d3;
}

Output

B : 30
D1 : 60
D2 : 70
D3 : 80

Now, D3 have only one copy of B and statement 4 will overwrite the value of b, given in statement 3.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements