How do I properly express two derived class functions with the same implementation in C++?
Add an intermediate proxy class:
class BC : public A {
void foo1();
};
class B : public BC {
void foo2();
};
class C : public BC {
void foo2();
};
As @Fureeish mentioned - don't repeat yourself.
What to do, if amount of classes / functions is massive:
Do the same. In the worst case, you'll end with (roughly) the same amount of code, with more classes, but fewer functions. Even then this is a net win, because you've removed a lot of code redundancy, and while inheritance structure is worse, the code quality is much better. In practice, such dense "collision matrix" suggests something is wrong with the classes themselves. Maybe those intermediate classes you up end creating should be written in the first place? In all cases, reducing code redundancy is a big win.
I see two options:
Move the common code to some interface (possibly private) and simply call that interface inside your two functions.
Provide a default implementation and simply don't override it, i.e. instead of making
foo1
pure virtual, just implement the default behaviour there.
Obviously it is possible that there is no default way of doing what foo1
should do. Then I suggest sticking with the first option.