I understand and have read enough about the diamond problem which is solved by virtual inheritance. My question here is
"What does placing virtual next to a base class that you would be inheriting from actually mean"
class A { public: void Foo() {} };
class B : virtual public A {};
class C : virtual public A {};
class D : public B, public C {};
I wanted to know if my understanding is correct. In the statement
class D : public B, public C {}
The compiler will go over first base class B and notice that its inheriting virtually from class A
. The compiler will check if instance of class A is present if not it will create an instance of A that is derived by B . The compiler will then go over class C and notice that it inherits virtually from class A. However since its being inherited virtually by C and an instance of A is already present it wont include a new instance. Thus solving the diamond problem. Is this understanding correct ?
Yes, your understanding is correct. The D instance will be a composition of a C, a B and a single A instance.
Virtual inheritance means that the instance of the virtual base class is looked up at runtime by the instance of the derived class (through a pointer or offset). This makes it possible for the compiler to use a single shared A instance.
It would be hard to find scenarios where virtual inheritance is reasonable and even in those cases the problem can usually be solved with simpler language features and abstractions.