Suppose I have an interface class and a partial implementation class. Also, suppose that I absolutely do not want this partial implementation to inherit from the interface:
class interface {
virtual void fnA() const = 0;
virtual void fnB() const = 0;
};
class partialImplementation { //Do not want to inherit from interface!
void fnA() const {cout << "fnA from partial implementation" << endl;}
//fnB() not implemented
};
The idea is that I'm planning to make several new classes all inheriting the interface, but I want to implement the same fnA()
in each one. So, after inheriting the interface, maybe I could also inherit the partial implementation and hope that fnA()
gets implemented. For example,
class myClass : interface, partialImplementation {
//would like fnA() to be implemented by partialImplementation
void fnB() const {cout << "fnB from myClass" << endl;}
};
Of course, if you try to instantiate this class, you get this error:
main.cpp: In function 'int main()':
main.cpp:235:10: error: cannot declare variable 'm' to be of abstract type 'myClass'
main.cpp:201:7: note: because the following virtual functions are pure within 'myClass':
main.cpp:193:15: note: virtual void interface::fnA() const
Compilation failed.
After reading some other stackoverflow posts (like this one) it seems the only available solution is to do this:
class myClass : interface, partialImplementation {
public:
void fnB() const {cout << "fnB from myClass" << endl;}
void fnA() const {
partialImplementation::fnA();
}
};
In the linked post, the OP didn't mind typing three extra lines. But you could imagine that I actually want partialImplementation
to implement more than just one function, and that I could be typing this same boilerplate over and over every time I want to make a new class inheriting this interface.
Does anyone know a way to do this without requiring partialImplementation
to inherit from interface
?