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 B
s 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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…