Check http://ideone.com/wjRwi4 (and copied below)
But you might need to review how you're doing things:
- Decide whether to use function pointers (or static member pointers) or method pointers (then you need an object to run the method on).
- You probably need to think about how you want to apply this to a hierarchy.
- Alternatively you can try function objects (i.e. a class/struct with an operator() defined).
- Remember that is always easier if you create a typedef for the function/method pointer.
- Check http://www.parashift.com/c++-faq/pointers-to-members.html
The code:
#include <iostream>
using namespace std;
class Man;
class Dog{
public:
Man *man;
void (Man::*callbackFunc)(void);
void setCallback(Man *_man,void (Man::*_callbackFunc)(void)){
callbackFunc=_callbackFunc;
man=_man;
}
void bite();
};
class Man
{
public:
void haveDogBiteYou(){
Dog *myDog = new Dog();
myDog->setCallback(this,&Man::sayAh); // How???
myDog->bite();
}
void sayAh(){
cout << "AHHHHHH!";
}
};
void Dog::bite(){
(man->*callbackFunc)();
}
int main() {
Man m;
m.haveDogBiteYou();
return 0;
}