Search code examples
c++overridingmultiple-inheritancevirtual-functionsvirtual-inheritance

Is this example working with virtual inheritance in C++?


Could I do this?

class A {
public:
  virtual void aFoo() = 0;
};

class B : virtual public A {
public:
  virtual void aFoo() { ... }
};

class D : public A {};

class C : public B, virtual public D {};

The issue is with the implementation of aFoo() in B and the lack of it in C. When it comes to compiling I see this error:

error: no unique final overrider for ‘virtual void A::aFoo()’ in ‘C’

Shouldn't it be possible to override a pure virtual method of a virtual base class in B?


Just edited the example to match the actual use case. Now looking at it in this simplified way I am not quite sure if this is even possible, let alone good design.


Solution

  • You need virtual inheritance in this way:

    struct A {
        virtual int f() = 0;
    };
    struct B : virtual A {
        int f() { return 1; }
    };
    struct C : virtual A {};
    struct D : B, C {};
    
    int main() {
        D d;
        return d.f();
    }
    

    In the dupe I commented you can see this relation

      A  
     / \  
    B   C  
     \ /  
      D 
    

    for virtual inheritance and

    A   A  
    |   |
    B   C  
     \ /  
      D 
    

    without virtual inheritance.

    In the second case D contains two function definitions. One is implemented and one isn't.