How to Pass a Function to Structure in C++?

Viewed 78

My Struct Code :

struct MouseHandler
{
    void OnHover();
    void* OnLeftClick();
    // void (*OnLeftClick)();
    void OnRightClick();
    void OnDrag();
    void OnDrop();
};

Calling of Struct :

MouseHandler ms;

I am trying to pass SampleScrollDownClickHandler to ms.OnRightClick(), Is it is possible, How can I do that, I am tried this, but I failed :

ms.OnRightClick() = SampleScrollDownClickHandler();

I am not using std library!

2 Answers

The member variables of the struct are not defined correctly.

void OnHover(); declares a member function, not a member variable. You need to use void (*onHover)();, which can point to a non-member function.

struct MouseHandler
{
    void (*OnHover)();
    void (*OnLeftClick)();
    void (*OnRightClick)();
    void (*OnDrag)();
    void (*OnDrop)();
};

With that change, you can use:

MouseHandler me;
me.OnRightClick = SampleScrollDownClickHandler;

as long as SampleScrollDownClickHandler is declared and is the right function type.

So the commented out line is actually closer to the solution you want. In order to pass the function pointer you need to not call the function itself, which you did by invoking it with the trailing (). So the following code is closer to what you want (limiting it just to the most basic parts of your code):

struct MouseHandler {
    void (*OnLeftClick)();
    void OnRightClick();
    void OnDrag();
    void OnDrop();
};

void my_callback() {
}

int main() {
    MouseHandler m;

    m.OnLeftClick = my_callback;
}
Related