A virtual base class in C++ is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritances. It is a base class that cannot be instantiated, meaning you cannot create direct objects out of it. When a base class is specified as a virtual base, it can act as an indirect base more than once without duplication of its data members. This means that only one copy of data/function member will be copied to the derived classes, and the virtual base class offers a way to save space and avoid ambiguities in class hierarchies that use multiple inheritances.
To declare a virtual base class, the keyword "virtual" is placed before or after the access specifier "public" in the derived class. For example, the syntax for virtual base classes can be written as:
- Syntax 1:
class B : ... virtual public A { };
- Syntax 2:
class C : public virtual A { };
In the above example, class A is inherited in both class B and class C, and it is declared as a virtual base class to resolve ambiguity when calling a member function of class A. By using virtual base classes, the derived classes get only one copy of the data, and the base class becomes the virtual base class.
Here is an example code snippet that demonstrates the use of virtual base classes in C++ :
#include <iostream>
using namespace std;
class A {
public:
int a;
A() {
a = 10;
}
};
class B : public virtual A {
};
class C : public virtual A {
};
class D : public B, public C {
};
int main() {
D object;
cout << "a = " << object.a << endl;
return 0;
}
In the above code, class A is inherited virtually by both class B and class C, and class D is derived from both class B and class C. The output of the program is a = 10
, which shows that only one copy of the data member a
is inherited by class D.