Sharing common code between derived classes in C++

Viewed 212

I'm having trouble when trying to share common code between derived classes in the below example:

class BaseWrite {
    public:
    virtual void setup() {}
};

class Write : public BaseWrite {
    public:
    void show() {
        cout << "Show Write" << endl;
    }
    virtual void print() {
        cout << "print Write" << endl;
    }    
};

class CompWrite : public Write {
    public:
    void compFunc() {
        cout << "compFunc details" << endl;
    }
};

//These below "Special" classes are in a separate file and are conditionally included while building the project

class SpecialWrite : public Write {
    public:
    void setup() override {
        cout << "print SpecialWrite setup()" << endl;
    }
};

class SpecialCompWrite : public CompWrite {
    public:
    //any common functions
};

In the above example, a CompWrite (or SpecialCompWrite) object should be able to access all the functions of Write class and also the setup() implementation that is being overridden in SpecialWrite class.

The constraint is, I cannot move up the setup function from SpecialWrite class to the Write class or BaseWrite class. And if it helps the context, the "Special*" classes are in a separate file and are conditionally included while building the project.

One way is I can simply override the setup function in SpecialCompWrite class as well and copy the code from SpecialWrite class. But I'm trying to avoid that.

1 Answers

If CompWrite has access to all public functions in SpecialWrite then a multiple inheritance could solve the problem, but both classes inherit from Write so the inheritances must be changed to virtual, the CompWrite class will look like:

class CompWrite : public Write, public SpecialWrite {

If the setup() function is the only function that needs to be accessible maybe a new class that both SpecialWrite and CompWrite inherit could solve it.

class SetupWrite : public Write {
    public:
    void setup() override {
        cout << "print SpecialWrite setup()" << endl;
    }
};

...

class CompWrite : public SetupWrite {
    public:
    void compFunc() {
        cout << "compFunc details" << endl;
    }
};

...

class SpecialWrite : public SetupWrite {
    public:
    // Other functions
};
Related