In C++, is it possible to have a base plus derived class implement a single interface?
For example:
class Interface { public: virtual void BaseFunction() = 0; virtual void DerivedFunction() = 0; }; class Base { public: virtual void BaseFunction(){} }; class Derived : public Base, public Interface { public: void DerivedFunction(){} }; void main() { Derived derived; }
This fails because Derived can not be instantiated. As far as the compiler is concerned Interface::BaseFunction is never defined.
So far the only solution I’ve found would be to declare a pass through function in Derived
class Derived : public Base, public Interface { public: void DerivedFunction(){} void BaseFunction(){ Base::BaseFunction(); } };
Is there any better solution?
EDIT: If it matters, here is a real world problem I had using MFC dialogs.
I have a dialog class (MyDialog lets say) that derives from CDialog. Due to dependency issues, I need to create an abstract interface (MyDialogInterface). The class that uses MyDialogInterface needs to use the methods specific to MyDialog, but also needs to call CDialog::SetParent. I just solved it by creating MyDialog::SetParent and having it pass through to CDialog::SetParent, but was wondering if there was a better way.
C++ doesn’t notice the function inherited from Base already implements
BaseFunction: The function has to be implemented explicitly in a class derived fromInterface. Change it this way:If you want to be able to get away with only implementing one of them, split
Interfaceup into two interfaces:Note: main must return int
Note: it’s good practise to keep
virtualin front of member functions in the derived that were virtual in the base, even if it’s not strictly required.