Introduction

Virtual base classes in C++ are used to prevent multiple instances of a given class from appearing in an inheritance hierarchy when using multiple inheritances.

Base classes are the classes from which other classes are derived. The derived(child) classes have access to the variables and methods/functions of a base(parent) class. The entire structure is known as the inheritance hierarchy.

Virtual Class is defined by writing a keyword “virtual” in the derived classes, allowing only one copy of data to be copied to Class B and Class C (referring to the above example). It prevents multiple instances of a class appearing as a parent class in the inheritance hierarchy when multiple inheritances are used.

Need for Virtual Base Class

To prevent the error and let the compiler work efficiently, we’ve to use a virtual base class when multiple inheritances occur. It saves space and avoids ambiguity.

When a class is specified as a virtual base class, it prevents duplication of its data members. Only one copy of its data members is shared by all the base classes that use the virtual base class.

If a virtual base class is not used, all the derived classes will get duplicated data members. In this case, the compiler cannot decide which one to execute.

Syntax

class B: virtual public A
// statement 1};
class C: public virtual A
// statement 2};

Examples

Example 1

#include <iostream>
using namespace std;
class A
{
  public:    A()
{
        cout << "Constructor A\n";
  }
void display()
{  
  cout << "Hello form Class A \n";
    }
};
class B: public A {};
class C: public A {};
class D: public B, public C {};
int main()
{
  D object;
  object.display();
}

Output:

/tmp/Fi0wBJsbRX.cpp:20:10: error: request for member 'display' is ambiguous
  20 |   object.display();
      |          ^~~~~~~
/tmp/Fi0wBJsbRX.cpp:9:6: note: candidates are: 'void A::display()'
    9 | void display()
      |      ^~~~~~~
/tmp/Fi0wBJsbRX.cpp:9:6: note:                 'void A::display()'

write your code here: Coding Playground

Example 2

#include <iostream>
using namespace std;
class A
{
  public:    A() // Constructor
  {
        cout << "Constructor A\n";
    }
};
class B: public virtual A
{
};
class C: public virtual A
{
};
class D: public B, public C
{
};
int main()
{
  D object; // Object creation of class D.
  return 0;
}

Output:

Constructor A

write your code here: Coding Playground