How Can I Pass a Member Function to a Function Pointer?

You can’t. You either pass a pointer to a static method or Parent has to accept also a pointer to the object.

You might want to look at boost::bind and boost::function for that:

#include <boost/bind.hpp>
#include <boost/function.hpp>
struct Y
{
    void say(void) { std::cout << "hallo!";}

    boost::function<void()> getFunc() { return boost::bind(&Y::say, this); }
};

struct X
{
    //non-boost:
    void (Y::*func)();
    Y* objectY;
    void callFunc() { (objectY->*func)(); }

    //boost version:
    boost::function<void()> f;

};


X x;
Y y;
x.f = boost::bind(&Y::say, boost::ref(y));
x.f = y.getFunc();
x.f();
x.func = &Y::say;
x.objectY = &y; 
x.callFunc();

Leave a Comment