user2487382
user2487382

Reputation:

How to get rid of duplicate code in derived classes?

I have a class hierarchy like:

class A {    
    list<A*> children;
public:
    void update() {
        do_something();
        update_current();
        for(auto child : children)
            children->update();
    }
protected:
    virtual void update_current() {};
};

class B : public A {
protected:
    void update_current() override {
        do_something_important();
    };
};

class C1 : public B {
protected:
    void update_current() override {
        B::update_current();
        do_something_very_important();
    };
};

class C2 : public B {
protected:
    void update_current() override {
        B::update_current();
        do_something_very_important_2();
    };
};

int main() {
    A* a = new A();
    //fill a's childred list somehow
    while(come_condition) {
        //some code
        a.update();
        //something else
    }
    return 0;
}

The question is: how can I remove duplicate B::update_current(); calls from derived classes without changing program's behaviour? Is it possible or are there no solutions except calling base class functions manually? Thank you.

Upvotes: 1

Views: 286

Answers (1)

Barry
Barry

Reputation: 303337

You could make B's children override a different function:

class B : public A {
protected:
    void update_current() override final {
        do_something_important();
        do_something_important_later();
    };

    virtual void do_something_important_later() = 0;
};

With:

class C2 : public B {
protected:
    void do_something_important_later() override {
        do_something_very_important_2();
    };
};

Upvotes: 3

Related Questions