1

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?

Community
  • 1
  • 1
C.P.
  • 11
  • 2
  • Pointers to non-static member functions are not the same as a pointer to a non-member function. I recommend you look into [`std::function`](http://en.cppreference.com/w/cpp/utility/functional/function) and [`std::bind`](http://en.cppreference.com/w/cpp/utility/functional/bind) instead. – Some programmer dude Nov 03 '16 at 12:00
  • It should be `void(DecltypeEventHandler::*f)(void)`. – skypjack Nov 03 '16 at 12:02
  • @skypjack: can't use that because I can't include the type in that class (include-loop). That's why I try to use the function pointer... – C.P. Nov 03 '16 at 12:06
  • @C.P. Well, a pointer to function and a pointer to member function are really different beasts. – skypjack Nov 03 '16 at 12:08
  • @skypjack: Ok. I changed the question. I need a pointer to a member function (of another object) – C.P. Nov 03 '16 at 12:09
  • @C.P. In order for a pointer-to-member to be usable, C++ has to know what it's a member of. If you can't actually provide that then you'll need to make your class and/or its constructor `template`'d. – Olipro Nov 03 '16 at 12:19

1 Answers1

1

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621