Suppose there is this interface:
class A{
public:
virtual foo()=0;
};
And a class B
which implements this interface:
class B:public A{
public:
virtual foo(){} //Foo implemented by B
}
Finally, a class C
which has classes A
and B
as base classes:
Class C : public A, public B {
};
My question is, there is a way to tell the compiler that the implementation for foo
is the one from class B
without doing an explicit call to B::foo()
?
As @BenVoigt pointed out in the comments, the below answer only works due to a bug in g++ (meaning it isn't guaranteed to keep working, and it definitely isn't portable). Thus, although it may do what you want if you use a particular (buggy) compiler, it isn't an option you should use.
Do use virtual inheritance though.
This isn't exactly the scenario that the code in the question implies, but the sentence
My question is, there is a way to tell the compiler that the
implementation for foo is the one from class B without doing an
explicit call to B::foo()?
seems to be asking for syntax to distinguish between multiple base versions of a function without using the ::
qualifier.
You can do this with the using
directive:
#include <iostream>
class A {
public:
A(){}
virtual void foo(){std::cout<<"A func";}
};
class B: virtual public A {
public:
B(){}
virtual void foo(){std::cout<<"B func";}
};
class C:virtual public A, virtual public B {
public:
C(){}
using A::foo; // tells the compiler which version to use
// could also say using B::foo, though this is unnecessary
};
int main() {
C c;
c.foo(); // prints "A func"
return 0;
}
Of course, the code itself in the question doesn't require this at all, as the other answers have pointed out.
Just use virtual inheritance, so that the A
subobject provided by B
is the same object used in C
.
Or write class C : public B
... it will be implicitly usable as an A
anyway, via the base class B
.
Before the question was edited:
B::foo
is not compatible with A::foo
.
The required signature is
ReturnType /* missing from question */ foo(A* const this /* this parameter is implicit */);
But B::foo
has the signature
ReturnType foo(B* const this);
An A*
, which will be passed to the virtual function, is not a B*
, which the implementation requires. If B
inherited from A
, then the compiler would generate B::foo
to accept an A* const subobject
and find the B* const this
object from that subobject pointer. But B::foo
has no knowledge of the relationship in C
.
As you have the two base classes in your example (which might be a design issue/design smell, I'd review that) you have to explicitly call the implementation that you are after, be it A::foo()
or B:foo()
.
If all B does is to provide the implementation of foo()
I'd consider moving the implementation into A (you can provide an implementation for a pure virtual function) but even in this case you'd have to call it via its qualified name.