C.P.
C.P.

Reputation: 11

Pass an objects member function as argument (function pointer)

I have a pointer to an object 'eventHandler' which has a member function 'HandleButtonEvents':

I call it like this:

eventHandler->HandleButtonEvents();

Now I want to pass a pointer to the member-function 'HandleButtonEvents()' of the class 'EventHandler' as an argument to another the object 'obj' like in this Stackoverflow example:

ClassXY obj = ClassXY(eventHandler->HandleButtonEvents);

The constructor is declared like this:

ClassXY(void(*f)(void));

The compiler tells me:

error : invalid use of non-static member function

What am I doing wrong?

Upvotes: 1

Views: 1056

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409356

Using std::function and std::bind as suggested in my comment makes it very easy:

#include <iostream>
#include <functional>

class ClassXY
{
    std::function<void()> function;

public:
    ClassXY(std::function<void()> f)
        : function(f)
    {}

    void call()
    {
        function();  // Calls the function
    }
};

class Handler
{
public:
    void HandleButtonEvent()
    {
        std::cout << "Handler::HandleButtonEvent\n";
    }
};

int main()
{
    Handler* handler = new Handler;

    ClassXY xy(std::bind(&Handler::HandleButtonEvent, handler));

    xy.call();
}

See here for a live example.

Upvotes: 1

Related Questions