Question:
What is it and why is it used in C++?
Answer:
Virtual inheritance is necessary in such a situation.
class A { int a; };
class B: public A {};
class C: public A {};
class D: public B, public C {};
In class D
, in this case, there will be two fields named a
and they will both belong to class A
. The problem is in determining which variable is being accessed. To avoid this situation, virtual inheritance is used. The correct form of the declaration in this example would be
class A { int a; };
class B: public virtual A {};
class C: public virtual A {};
class D: public B, public C {};