Search code examples
c++virtual

"dreaded diamond" with polymorphism


I have the following code:

class Base
{
    public:
        virtual void doSomething() = 0;
};

class BaseImpl : public virtual Base
{
    public:
       virtual void doSomething() {
       // something
       }
};

class BaseDerived: public virtual Base
{
    public:
       virtual void doSomething2() = 0;
};

class BaseDerivedImpl: public BaseImpl, public BaseDerived
{
    public:
       virtual void doSomething2(){
       // sonething2
       }
};

Then I have

Base* b = new BaseImpl();
b->doSomething();          // fatal error at this line (not in the method, but in the method invocation)

The problem is that it even does not go into the function.

Is it something wrong with using such hierarchy?


Solution

  • As OP ignores the comments, let me answer the question here:

    Is it something wrong with using such hierarchy?

    No, nothing is wrong. This is the standard way how to solve the 'dreaded diamond' issue (which isn't actually all that dreadful).

    However, the diamond doesn't even come to play in this example:

    Base* b = new BaseImpl();
    

    BaseImpl is derived directly from Base so you have standard single inheritance. Your code behaves the same as if BaseDerived and BaseDerivedImpl were not defined at all. You can comment them out, and the app will still crash.

    Then you call doSomething on this instance and it crashes. The implementation of doSomething is as follows:

    // something
    

    Thus, my conclusion is that // something results with crash, but it is impossible to tell without seeing the implementation of that method.