1

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.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
  • You shouldn't inherit from A and B if B already inherits from A. Thats wrong. And as the error message says, you have to override Foo from A, because you inherit directly from it. (assuming the top class, where code is missing, is class A) – RoQuOTriX May 05 '20 at 08:10
  • I see, I made a mistake in the example. C is supposed to implement another type, D, which is again inheriting A virtually. I will fix that, I'm very sorry for the confusion here. – AAAAAAAAARGH May 05 '20 at 08:14
  • Does this answer your question? [How does virtual inheritance solve the "diamond" (multiple inheritance) ambiguity?](https://stackoverflow.com/questions/2659116/how-does-virtual-inheritance-solve-the-diamond-multiple-inheritance-ambiguit) – Thomas Sablik May 05 '20 at 08:17
  • Which compiler gives you that error? It's fine [here](http://coliru.stacked-crooked.com/a/7ac9c6297841d5b4) – Caleth May 05 '20 at 08:20
  • Thomas, thanks for the link. My question is more about the usage of pure virtual functions within the diamond problem. I'm afraid the answers there do not quite lead to any information about this. – AAAAAAAAARGH May 05 '20 at 08:21
  • Caleth, this is GCC 9.3.0. I believe you test is compiling because you did not try to instantiate C. – AAAAAAAAARGH May 05 '20 at 08:24
  • RoQuOTriX Thank you for your comment, but shouldn't the virtual method inherited from B be already sufficient? At least that's what I thought would happen when using virtual base classes like this. – AAAAAAAAARGH May 05 '20 at 08:28

1 Answers1

1

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.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62