0

What happens if, in a large chain of inheritances, the virtual keyword is at some point forgotten?

For example:

struct I {};

struct A : virtual I {};

struct B : A, virtual I {};

struct C : B, /* virtual */ I {};   // ooops, distraction error

Is it like in the methods case, that once a method is virtual it stays virtual forever, or is the struct C reintroducing the diamond problem?

Is there a way to make the compiler check for this type of errors, in a similar way the new override keyword is checking for the correct overriding of the virtual methods?

nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64
  • How would the compiler know that this is an error? It's perfectly valid and reasonable code. Also, why would you be using virtual inheritance so much? – Nicol Bolas Mar 08 '16 at 15:22
  • From the compiler view, it is not an error, and such code is reasonable (ish)? In all my years of coding never in my life I had to deal with diamond inheritance outside of the interview room. I think, if you have designed your system with such inheritance, just go back and redesign. – SergeyA Mar 08 '16 at 15:26
  • What happens is that your unit tests fail. – Pete Becker Mar 08 '16 at 15:27
  • @NicolBolas Why would you use non-virtual public inheritance so much? – curiousguy Mar 11 '16 at 21:09

2 Answers2

4

What happens here is as follows:

  1. A gets I as part of its memory
  2. B gets exactly A as part of its memory
  3. C gets exactly B plus an extra I as part of its memory

So it's not a diamond, but more like a broken fork:

I
|
A
|
B   I
 \ /
  C

Also, it's not strictly an error—at least not a compilation error—but a feature of the language.

As for avoiding it, you should probably restrict your virtual inheritance work to when you're really focused anyways, and/or avoid it as much as you can.

Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38
0

What happens if, in a large chain of inheritances, the virtual keyword is at some point forgotten?

struct A : virtual I {};

struct B : A, virtual I {};

Why would you even "reintroduce" I? It is already a virtual base class. You are just being redundant.

There is no reason to do that. The only possible reason would be to relax access control (or gain access to a private virtual base class), and the base class is already public here.

So the question is just meaningless. You can't forget a second virtual in a chain of inheritance when you never repeat the base class name.

curiousguy
  • 8,038
  • 2
  • 40
  • 58