views:

33

answers:

1

Say we have a class inheriting from two base classes (multiple inheritance). Base class A is abstract, declaring a pure virtual function foo, the other base class B declares and implements a function foo of the very same signature.

struct A
{
  virtual void foo(int i) = 0;
};

struct B
{
  virtual void foo(int i) {}
};

struct C : public A, public B {};

I want to use the implementation of foo from base class B in my derived class C. However, if I do not implement the function foo a second time in my derived class C, I cannot instantiate any object of it (it remains abstract). Virtual inheritance does not help here as expected (class A and class B have no common base class).

I wonder if there is a way to "import" the implementation of foo from class B into class C in order not to have to repeat the same code.

Above example is of course contrived. The reason I want implement foo in class B is that I want to derive class D : public B and use class Bs implementation of foo. I know that inheritance is not (primarily) intended for code reuse, but I'd still like to use it in that way.

+1  A: 

In java, your sample code works. In C++ it doesn't. A subtle difference between those languages.

Your best option in C++ is to define C::foo() by forwarding to B::foo():

struct C : public A, public B
{
  virtual void foo(int i) { B::foo(i); }
};
Sjoerd
That sounds like a viable option at least, thanks!
kynan