Search code examples
c++inheritancevirtual-inheritancediamond-problem

Virtual Inheritance: what happens if the keyword is at some point forgotten?


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?


Solution

  • 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.