Showing posts with label function pointers. Show all posts
Showing posts with label function pointers. Show all posts

Wednesday, December 01, 2010

some fun with C++

Was playing around with C++, and found that you can actually use a base class member function pointer to call functions defined in derived class. Round about way, but useful for implementing stuff like: http://en.wikipedia.org/wiki/Future_%28programming%29

Here is an example snippet:

#include ...
class Base {
public:
typedef void (Base::*WhoPtr)();
};
class D1: public Base {
public:
void WhoAmI() const;
};
class D2: public Base {
public:
void WhoAmI() const;
};
void D1::WhoAmI() const {
std::cout << "I am D1" << std::endl;
}
void D2::WhoAmI() const {
std::cout << "I am D2" << std::endl;
}
void run(Base::WhoPtr fptr) {
Base base;
(base.*fptr)();
}
int main(int argc, char **argv ) {
Base::WhoPtr func;
func = (void (Base::*)()) &D1::WhoAmI;
run(func);
func = (void (Base::*)()) &D2::WhoAmI;
run(func);
return 0;
}