C ++ virtual inheritance difference

For two classes with a common virtual base class:

class Base {}; class Derived1 : public virtual Base {}; class Derived2 : public virtual Base {}; 

Is there a difference between these two additional derived classes:

  •  class Derived3 : public virtual Base, public Derived1, public Derived2 {}; 
  •  class Derived3 : public Derived1, public Derived2 {}; 

The first also comes directly from the virtual base class, but I think this has no effect, because it shares with Derived1 and Derived2 .

+5
source share
3 answers

They say the same thing. The only difference is that if you removed public Derived1 and public Derived2 from both Derived3 definitions, the first one would still inherit from Base , and the second would not.

EDIT: I did not think about whether there is any strange situation with cross situations where they will behave differently, although I do not think so.

+2
source

There is no difference between these examples.

But in a more complex scenario, direct inheritance of an inherited virtual database can change the order of construction / destruction of subobjects of the base class.

+2
source

I don't think there is any difference in the layout of the object, because the intention of virtual inheritance is to avoid two copies of Base (or three instances in case 1).

So, the whole difference is in your intentions and really readability of the code.

+1
source

All Articles