136
136

Reputation: 1207

C++ How to implement callbacks?

I'm trying to implement a Button class in C++. Here's how it's going so far:

button.h:

class Button {
    private:
        unsigned short x;
        unsigned short y;
        std::string text;
        std::function<void()> onClickFunction;
    
    public:
        Button(unsigned short x, unsigned short y, std::string text, std::function<void()> onClickFunction);
        void onClick();

button.cpp:

Button::Button(unsigned short x, unsigned short y, std::string text, std::function<void()> onClickFunction)
{
    this->x = x;
    this->y = y
    this->text = text;
    this->onClickFunction = onClickFunction;
}

void Button::onClick()
{
    this->onClickFunction();
}

However, when I try to create a button, such as:

this->toggleGridButton = Button(x, y, "Toggle Grid", &Engine::toggleGrid);

I get the following error:

no instance of constructor "Button::Button" matches the argument list -- argument types are: (int, int, const char [12], void (Engine::*)())

How can I make a callback to a member function?

Upvotes: 0

Views: 277

Answers (1)

Jarod42
Jarod42

Reputation: 217265

You probably want:

this->toggleGridButton = Button(x, y, "Toggle Grid", [this]() { this->toggleGrid(););

Upvotes: 1

Related Questions