5

Given two classes with a common virtual base class:

class Base {};

class Derived1 : public virtual Base {};

class Derived2 : public virtual Base {};

Is there any difference between these two further derived classes?:

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

The first also derives directly from the virtual base class, but I think that has no effect, because it's shared with Derived1 and Derived2.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
quazeeee
  • 323
  • 2
  • 14

3 Answers3

2

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

EDIT: I haven't thought carefully about whether there is some weird cross-cast situation where the two would also behave differently, although I don't think there is.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
2

There is no difference between those examples.

But in a more complicated scenario, directly inheriting an otherwise inherited virtual base might change the order of construction / destruction of the base class subobjects.

aschepler
  • 70,891
  • 9
  • 107
  • 161
1

I do not think there is any difference in object layout because the intention of virtual inheritance is to avoid having two copies of Base (or three copies in case 1).

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

Alexander Balabin
  • 2,055
  • 11
  • 13