Let's consider two classes A
and B
with the following interface:
class A {
public:
virtual void start() {} //default implementation does nothing
};
class B {
public:
void start() {/*do some stuff*/}
};
and then a third class which inherits from both, A
publicly because it implements this "interface", and B
privately because that's implementation detail.
However, in this specific implementation, start()
only has to contain a call to B::start()
. So I thought I could use a shortcut and do the following:
class C: public A, private B {
public:
using B::start;
};
and be done with it, but apparently it doesn't work. So I get using
private base function doesn't work in order to override virtuals. From that, two questions:
- Is there any way to make this work as I supposed it may have worked?
- Why would the compiler accept this code as valid? As I see it there are now two
start()
functions with the exact same signature inC
and yet the compiler seems fine with it and only callsA::start()
.
EDIT: A few precisions:
- The goal is to manipulate
C
objects throughA
pointers. - I'm currently using a simple function that just calls
B::start()
, I was specifically wondering if a using declaration could indeed "override" a virtual, and if not, how this was allowed to have both functions coexist. - I might have omitted a few things like
virtual
inheritance for simplicity.
You should override the member function and explicitly call
B::start()
:You are right, there are two member functions accessible in C (
A::start()
andB::start()
). And inclass C
, without overridingstart()
or making thestart()
of any of the base classes visible by doing ausing ...::start()
, you will have ambiguity error when trying to call the member function using unqalified namelookup from an object ofC
.To fix that, you will have to use the qualified name such as:
Now, doing a
using B::start()
inclass C
simply declares thestart()
to refer toB::start()
whenever such name is used from an object ofC
using B::start
makes the functionvoid B::start()
visible inC
, it does not override it. To call make all the above unqualified member function call, to callB::start()
, you should override the member function inC
, and make it callB::start()