C ++: virtual functions that should call the same code?

I have a base class and classes that derive from it. The base class Controllableacts as an interface for the input loop, and other classes are extracted from it to get a spot in this loop to receive events such as if a key were pressed.

class Controllable{
public:
    virtual void setActive(bool state) { m_active = state; }
    virtual void input(Event & e) =0;
private:
    bool m_active;
};

class Button : public Controllable{
public:
    void setActive(bool state){ /*do extra work*/ m_active = state; }
    void input(Event & e) override;
};

Since the class Buttondeals with events from the event queue, setting it to inactive (which removes it from the input loop) can lead to the omission of important events, such as a keystroke, so this requires additional code to put it in a friendly inactive state if it will become active again later.

, , setActive m_active , , ?

+5
5

setActive , protected activeChanged,

class Controllable{
public:
    void setActive(bool state) { m_active = state; activeChanged(state); }
    virtual void input(Event & e) = 0;
protected: 
    virtual void activeChanged(bool newState) {}
private:
    bool m_active;
}

class Button : public Controllable{
protected:
    void activeChanged(bool newState){ /*do extra work*/ }
public:
    void input(Event & e);
};

, .

+9

- "pre" "post":

class Controllable{
public:
    void setActive(bool state) {
        preSetActive(m_active, state);
        m_active = state;
        postSetActive(m_active);
    };
    virtual void input(Event & e) =0;
protected:
    virtual void preSetActive(bool oldState, bool newState) {}
    virtual void postSetActive(bool newState) {}
private:
    bool m_active;
}

, setActive() .

+6

Basically, your case is based on a template template template .

+2
source

How to make it setActive()not virtual, but instead add a second virtual member (for example onSetActive()) that is called setActive()?

+1
source

My 2 cents: share your behavior between two tasks:

virtual doActive(){}; //doNothing
void setActive (bool state) {
    m_active = state;
    doActive();
}
+1
source

All Articles