I have a need to be able to have a super class execute callbacks defined by a class that inherits from it. I am relatively new to C++ and from what I can tell it looks like the subject of member-function-pointers is a very murky area.
I have seen answers to questions and random blog posts that discuss all sorts of things, but I am not sure if any of them are specifically dealing with my question here.
Here is a simple chunk of code that illustrates what I am trying to do. The example might not make a lot of sense, but it accurately resembles the code I am trying to write.
class A { protected: void doSomething(void (A::*someCallback)(int a)) { (*this.*someCallback)(1234); } }; class B : public A { public: void runDoIt() { doSomething(&B::doIt); } void runDoSomethingElse() { doSomething(&B::doSomethingElse); } protected: void doIt(int foo) { cout << 'Do It! [' << foo << ']\n'; } void doSomethingElse(int foo) { cout << 'Do Something Else! [' << foo << ']\n'; } }; int main(int argc, char *argv[]) { B b; b.runDoIt(); b.runDoSomethingElse(); }
If you can use boost libraries, I would suggest you use boost::function for the task at hand.
Then any inheriting (or external class) can use boost::bind do make a call:
I have not checked the exact syntax and I have typed it from the top of my head, but that is at least close to the proper code.