Virtual inheritance is a C++ technique that ensures only one copy of a base classs member variables are inherited by grandchild derived classes. In C++, a class can inherit from multiple classes, which is commonly referred to as multiple inheritance. However, this can cause problems sometimes, as you can have multiple instances of the base class. To tackle this problem, C++ uses a technique that ensures only one instance of a base class is present, which is referred to as virtual inheritance.
Virtual inheritance is used when inheritance represents restriction of a set rather than composition of parts. It is almost never needed, but it addresses the diamond inheritance problem that arises due to multiple inheritance. The diamond problem occurs when two classes inherit from the same base class, and a third class inherits from both of these classes. This can cause ambiguity when accessing data or function members of the base class.
To inherit virtually, we add the keyword "virtual" before the base class name in the derived class declaration. For example, class B : virtual public A{}
. Inheriting virtually guarantees that there will be only one instance of the base class among the derived classes that virtually inherited it.
It is important to note that constructors for virtual base classes are always called by the constructor of the concrete class, not by the class that inherits from it.