Search code examples
c++inheritancevirtual

C++ Virtual Inheritance weird behavior


struct A {
public:
    A() {
        std::cout << "A" << std:: endl;
    }
    void foo() { std::cout << "foo is called from A"; }
};

struct B : virtual A {  };
struct C : virtual  A {  };
struct D : B, C { D() { std::cout << "D" << std::endl; } };

struct E : D { };
struct F : D {};
struct G : E, F {}; 


int main()
{
    G g;
    g.foo();
}

The output code is :

  • A
  • D
  • D
  • foo is called from A

This makes no sense. Object D is constructed twice. Why doesn't the compiler complain that foo is ambiguous? How does G know that there is only one definition on foo ? (in this case D is made twice and I did not use virtual inheritance but somehow it knows.) I honestly thought that E and F should inherent also virtually from D in order to avoid the ambiguous definition of foo. Can anyone offer a good explanation? Compiled in VS 2017 Windows. You can imagine this line of inheritance as a double diamond problem.


Solution

  • This makes no sense.

    Why? This is exactly what virtual inheritance is for. There is only a single A sub-object inside G. The specifier sticks as we go down the hierarchy, so even though G has two D's, they both share an A.