3

Consider the following code:

struct A
{
  virtual void f() = 0;
};

struct B
{
  void f();
};

struct C : public A, public B
{};

int main()
{
  A* a = new C();
  B* b = new C();
  C* c = new C();

  // All these calls should result in B::f
  a->f();
  b->f();
  c->f();
}

The compiler states that C is abstract. How can this situation be resolved? The issue seems similar to diamond inheritance, but I fail to see the solution.

EDIT: Thanks, this is the working example:

#include "stdio.h"

struct A
{
  virtual void f() = 0;
};

struct B
{
  void f()
  {
      printf("B::f\n");
  }
};

struct C : public A, public B
{
  void f()
  {
      printf("C::f\n");
      B::f();
  }
};

int main()
{
  A* a = new C();
  B* b = new C();
  C* c = new C();

  printf("Calling from A\n");
  a->f();
  printf("Calling from B\n");
  b->f();
  printf("Calling from C\n");
  c->f();
}

Output:

Calling from A
C::f
B::f
Calling from B
B::f
Calling from C
C::f
B::f
Beta Carotin
  • 1,659
  • 1
  • 10
  • 27
  • Just to understand your intent: You want `A` to define an interface, `B` define an implementation and `C` putting them together? I don't see the advantage of this over `B : A`, since when implementing `B`, you already know the interface you are implementing, right? – leemes Jan 05 '13 at 22:12
  • I cant simply let `B` derive from `A`, since this is only an isolated example of a problem I encountered in a much bigger project. – Beta Carotin Jan 05 '13 at 22:31

2 Answers2

4

The issue is that the two f() functions are completely unrelated, even though they happen to have the same name.

If the desired behaviour is for the C's virtual f() to call B::f(), you have to do it explicitly:

struct C : public A, public B
{
  void f();
};

void C::f() {
  B::f();
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

You need to override the virtual function from the base class in C. If you want it to call B::f, say it like this:

struct C : A, B
{
    void f() { B::f(); }
};
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084