How to create a Button class that swells on other class object

Viewed 42

I'm creating a little game in cpp, and I have trouble with my Button class:

class ids::Button : public ids::ASpriteObject {
    public:
        Button(std::vector<float> pos, std::string texture, int frame, std::function<void(Button&)> ptr, gameState &state);
        ~Button();
        std::string getType();
        void checkCollisions();
        void drawAsset(std::map<std::string, ModelS> modelMap);
        void launchGame();
        void settings();
        void exit();
        void mainMenu();
        void increaseSound();
        void decreaseSound();
        void increaseFPS();
        void decreaseFPS();

    protected:
    private:
        std::function<void(Button&)> _function;
        gameState &_gameState;
};

As you can see, a Button take a std::function in it's constructor. Thanks to it, I assign to the button the function which will be executed on click.

Here is my question: with my button, I want to modify other class object, like Text class for example:

class Text : public ids::AStaticObject {
    public:
        Text(std::vector<float> pos, std::string text, float size);
        ~Text();
        void drawAsset(std::map<std::string, ModelS> modelMap);

    protected:
    private:
        Font _font;
        std::string _text;
        Vector2 _pos;
        float _size;

};

on click, I want to modify the _text. I can pass a reference to my Text object to my Button, but it's not smart, eventually I should modify other objects with my button...

Thanks for your help!

1 Answers

Given a reference to a Text textObj, you can create a callback that keeps a reference to textObj as follows:

auto callback = [&textObj](Button& b) {
  textObj.setText("hi there");
};

auto buttonPtr = new Button(pos, texture, frame, callback, state);
// or assign it to an object instance variable
Related