I have 2 classes
class B {
public:
int func(int i);
};
class A {
public:
typedef int (B::*fPtr)(int);
void run();
B* mB;
};
void A::run() {
// create a pointer
fPtr p = &(B::func);
// invoke the function
mB->*p(2); <------- Compilation Error
}
What i need is to create a pointer to func() in A’s run function. I get a compilation error saying that mB is not corresponding to a function with 1 argument.
please help
Instance methods on a class always have a hidden first parameter for the
thispointer, thus it is incompatible with your function pointer typedef. There is no way directly to obtain a pointer to a member function. The typical workaround is to use a “thunk” where you pass a static function that accepts a generic “catch all” parameter (such asvoid *) which can be statically cast to a pointer of your choosing on which you can invoke the member function. Example:You can get a pointer to the static function easily as it has no ‘hidden
this‘, just reference it usingB::MyThunk. If your function requires additional parameters, you can use something like a functor to capture the necesssary parameters and state.You should definitely read this C++ FAQ Lite page which tells you much more about all this: Pointers to member functions