Virtual Base Class in C++

Virtual Base class is used to resolve the ambiguity in inheritance. While inheriting the base class data there may be a some situation where it may generate an error to access the base class data. Lets check a situation first and after we will discuss the answer for, what is base class ? and why it is used?

Scenario 1:

Hybrid Inheritance

Consider a situation, where all the three kinds of inheritance, namely multi-level, multiple and hierarchical are involved.

Let us say the ‘ClassD‘ has two direct base classes ‘ClassB’ and ‘ClassC’ which themselves has a common base class ‘ClassA‘. The child inherits the traits of ‘ClassA’ via two separate paths. It can also be inherit directly as shown by the broken line. The ClassA is sometimes referred to as ‘INDIRECT BASE CLASS’.

Now, the inheritance by the ClassD might cause some problems. All the public and protected members of ‘ClassA’ are inherited into ‘ClassD’ twice, first via ‘ClassB’ and again via ‘ClassC’. So, there occurs a duplicate data members which should be avoided.

virtual base class
virtual base class

How to resolve this ambiguity?

This situation can be avoided by making common base class ‘ClassA’ as the virtual base class using the virtual keyword in inheritance.

When a class is virtual base class, C++ takes necessary care to see that only one copy of that class is inherited, regardless of how many inheritance paths exists between virtual base class and derived class.

Syntax:

class A
{
//Body
};
class B: virtual public A
{
// Body
};
class C: public virtual A
{
// Body
};
class child:public B, public C
{
// body
};

Note that keywords ‘virtual’ and ‘public’ can be used in either order. Here, ClassA will be the virtual base class for both the ClassB and ClassC. So at last only one copy of the data will be inherited.

Related posts