views:

108

answers:

1

Suppose I have a diamond inheritance situation as follows:

class A{
    public: virtual void foo(){};
};
class B: public virtual A{
    public: virtual void foo(){};
};
class C: public virtual A{
    public: virtual void foo(){};
};
class D: B, C{};

The last line yields a compilation error citing ambiguity. As I understand it, the problem is that the compiler doesn't know which foo to place in D's vtbl, but why would there even be a vtbl for D if it doesn't define any virtual functions of its own?

+7  A: 

You're inheriting classes that contain virtual functions. Therefore, your class has virtual functions. It's as simple as that.

Corey D
Then maybe I'm missing something, because when I remove the word "virtual" from the inheritance specification (class B: A, class C: A), it compiles and runs. Shouldn't the problem presist because I'm "inheriting classes that contain virtual functions"?
EpsilonVector
Sorry that was class B: public A, and so on...
EpsilonVector
Remove the keyword `virtual` from the method declarations in `class B` and `class C`. Recompile and see what happens.
Thomas Matthews
@Thomas Sure, then we have no problem, but this is not the case I asked about. If inheriting from classes with virtual functions automatically results in a vtbl for the inheriting class, why is it that when I inherit with just "public" inheritance the problem disappears? I'm still inheriting from classes with virtual functions.
EpsilonVector
Because without the virtual in B and C's declaration, they do not share a common A ancestor but independent A entities.
Joe