C++: using a base class as the implementation of an interface
If Base
isn't derived from Interface
, then you'll have to have forwarding calls in Derived
. It's only "overhead" in the sense that you have to write extra code. I suspect the optimizer will make it as efficient as if your original idea had worked.
class Interface {
public:
virtual void myfunction() = 0;
};
class Base {
public:
virtual void myfunction() {/*...*/}
};
class Derived : public Interface, public Base {
public:
void myfunction() { Base::myfunction(); } // forwarding call
};
int main() {
Derived d;
d.myfunction();
return 0;
}
Try this:
class Interface
{
virtual void myfunction() = 0;
}
class Base : public Interface
{
virtual void myfunction() {/*...*/};
}
class Derived
: public Base
{
// myfunction is implemented by base
}