• Home
  • Virtual base class in C++

Virtual base class in C++

In C++, a virtual base class is a class that is intended to be shared among multiple derived classes. The main purpose of a virtual base class is to avoid the problem of ambiguity that can occur when a derived class is derived from multiple classes that have a common base class.

To declare a class as a virtual base class, the virtual keyword is used in the class’s inheritance list. For example:

class Base {
// class definition
};

class Derived1: virtual public Base {
// class definition
};

class Derived2: virtual public Base {
// class definition
};

In the above example, Base is declared as a virtual base class for both Derived1 and Derived2. This means that if Derived1 and Derived2 are both derived from a common class that also has Base as a base class, then there will be only one instance of Base shared among all three classes.

One important thing to note about virtual base classes is that they must be initialized by the most derived class in the inheritance hierarchy. For example:

class MostDerived: public Derived1, public Derived2 {
MostDerived(): Base(), Derived1(), Derived2() {}
// class definition
};

In the above example, the virtual base class Base must be initialized before the derived classes Derived1 and Derived2 are initialized. This ensures that there is only one instance of Base shared among all three classes.

Virtual base classes are a useful tool for avoiding ambiguity in inheritance hierarchies and for sharing common functionality among multiple derived classes.