Improve a C ++ class architecture where several classes derive from the same databases

advertisements

I have a C++ architecture where I have many classes that all derive from two distinct base classes. All of the derived classes override/implement the same methods in the base classes in slightly different ways. To illustrate:

class B1 {
public:
    // method_1 is pure virtual.
    virtual void method_1() = 0;
};

class B2 {
public:
    // method_2 is not pure virtual.
    virtual void method_2();
};

class D1 : public B1, public B2 {
public:
    virtual void method_1() { // Does something... }
    virtual void method_2() { // Does something... }
};

class D2 : public B1, public B2 {
public:
    virtual void method_1() { // Does something slightly different... }
    virtual void method_2() { // Does something slightly different... }
};

Everything works fine, but being as there are about 20 derived classes, it feels like there should be a way to improve this design so that I have to write less code, especially as the derived classes are often quite similar in what they're doing. Can anyone offer me any pointers for the future?


take a look at strategy design pattern. Basically make methods 1 and 2 wrappers over B1 and B2 classes owned by unique pointers by class D. Then you can pass B1 and B2 instances in a constructor of D.