Currently, I'm in a situation where I have some base class and many subclasses. The subclasses must override several virtual methods, however, sometimes the implementation for a virtual method in one subclass is exactly identical to another subclass. Should I just copy and paste the implementation code into the other subclass or is there a way to express an implementation for both subclasses at once?
The code below demonstrates my problem.
class A
{
virtual void foo1() = 0;
virtual void foo2() = 0;
};
class B : public A
{
void foo1();
void foo2();
};
class C : public A
{
void foo1();
void foo2();
};
class D : public A
{
void foo1();
void foo2();
};
void B::foo1()
{
// Same implementation of foo1 as C
}
void C::foo1()
{
// Same implementation of foo1 as B
}
void D::foo1()
{
// Different implementation of foo1
}
void B::foo2()
{
// Different implementation of foo2
}
void C::foo2()
{
// Different implementation of foo2
}
void D::foo2()
{
// Different implementation of foo2
}
Can I somehow combine implementation for B and C?
Note: I explicitly wrote out foo2, because otherwise subclass B and C would be identical in every way.
I'm wondering about the case when there are many (much larger than this toy example) subclasses and also they are inheriting many virtual functions with some virtual functions having the same implementation. In other words, a situation where creating a subclass every time a function coincidentally has the same implementation would clutter the whole inheritance structure.