Question

Consider the following hierarchy in C++ notation:

class A
    {
    public:
        virtual void doStuff()=0;
        virtual void doOtherStuff()=0;
    };

class B:public A
    {
    public:
        void doStuff();
        void doOtherStuff();
    };

class C:public A
    {
    public:
        void doStuff();
        void doOtherStuff();
    };

Now, assume that the code for doStuff is identical in B and C. What is the best practice of

  • implementing doStuff in a class D:public A and let B and C derive from A
  • Let the real task be performed in a function that is called from doStuff in both B and C

Somehow the latter seems more clean, is it? It should be noted that there are other methods in B and C with common implementations as well, and that in the underlaying model, the concept of D does not exist.

Was it helpful?

Solution

I would create a class E to hold the shared implementation of doStuff

class E : class A
{
override doStuff() {}
}

and have classes B and C inherit from E. This allows you to maintain the inheritance if B and C still need to be types derived from A, but allows A and other derivations to not share the same implementation and B and C

Licensed under: CC-BY-SA with attribution
scroll top