Virtual Base Class in C++ with an Example

In this tutorial, we will learn what is a virtual base class in C++. We will also see an example of how to implement it using C++.

Virtual base class in C++

In an inheritance hierarchy consisting of multiple inheritance, multiple paths are created to access base class instances and also a copy of the base class instances is created in each path. So, the compiler confuses between these paths and which copy to use.

We can solve this problem by using the virtual base class. A class becomes a virtual base class by using the keyword virtual while inheriting. By using virtual base class only a single copy of the base class instances is created.

Implementation in C++

Consider this situation, we have two classes derived1 and derived2 inheriting the class base. We also have a class derived3 inheriting derived1 and derived2 classes.

#include <iostream>
using namespace std;

class base
{
  public : int x;
  base()
  {
    cout<<"base\n";
  }
};

class derived1 : public base  // line 13
{
  public : int y;
  derived1()
  {
    cout<<"derived1\n";
  }
};

class derived2 : public base // line 22
{
  public : int z;
  derived2()
  {
    cout<<"derived2\n";
  }
};

class derived3 : public derived1,public derived2
{
  public : int p;
  derived3()
  {
    cout<<"derived3\n";
  }
};

int main ()
{
  derived3 d;
  d.x = 20;
  cout << d.x;
}

Let us now create an object for derived3 class and try to access the base class instance x. To access x we have two paths. One is through derived1 and the other is through derived2. So, the compiler confuses and shows an error.

Error:

43	4	[Error] request for member 'x' is ambiguous

We can resolve this problem by using the keyword virtual while inheriting the class base.

Replace line 13 with

class derived1 : virtual public base

and line 22 with

class derived2 : virtual public base

Now only a single copy of the base class instances is created and the confusion is resolved.

Output:

base
derived1
derived2
derived3
20

Also read, Inheritance in C++

Leave a Reply

Your email address will not be published. Required fields are marked *