class Child;
class Parent
{
public:
void (*funcPointer)();
void (*funcPointer2)(Parent* _this);
void (Child::*funcPointer3)();
};
class Child: public Parent
{
public:
void TestFunc(){
}
void Do(){
Parent p;
p.funcPointer=TestFunc; // error, '=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(void)'
p.funcPointer2=TestFunc; // error too, '=': cannot convert from 'void (__thiscall Child::* )(void)' to 'void (__cdecl *)(Parent *)'
p.funcPointer3=TestFunc; //this works
p.funcPointer3=&Child::TestFunc; // this works too.
p.funcPointer3(); // error, term does not evaluate to a function taking 0 arguments
}
};
How can I pass a member function to a function pointer, and then how would I then call that 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();
In response to your last edit, to form a pointer-to-member, you have to use &
and classkey::
. There's no equivalent to the function name to pointer-to-function implicit conversion for normal functions.
// not valid:
p.funcPointer3=TestFunc;
// valid:
p.funcPointer3 = &Child::TestFunc;
To access a member through a pointer-to-member you have to use either the .*
or ->*
operator.
E.g.
(this->*p.funcPointer3)();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With