Sign in to follow this  
Hermes

Pointers to functions

Recommended Posts

Hermes    144
Hi i have an array of pointers to functions in a class called Node,but i use many nodes and the functions are the same ;since speed is important i need to know a way to use that array as static(only one instance for all the nodes)but i don't know how to use the constructor to build my static array.Is the global array the only solution??.The functions are also members of the class. Thankx for your help!

Share this post


Link to post
Share on other sites
Cygon    1219
It is possible to have a static function pointer to a class method in your class. Check out this example:
//
// Your .h file
//

class Node {
public:
typedef (Node::*displayPtr)(const char *);

// Call the function pointer on this instance
int test() {
return (this->*display)("hello world");
}

// Set function pointer to first method
static void useCout() { display = &Node::displayCout; }
// Set function pointer to second method
static void useMessageBox() { display = &Node::displayMessageBox; }

private:
// The function pointer
static int (Node::*display)(const char *);

int displayCout(const char *msg) {
cout << msg << endl;
return 0;
}
int displayMessageBox(const char *msg) {
return MessageBox(NULL, msg, "Message", MB_OK);
}
};

//
// Your .cpp file
//

Node::displayPtr Node::display = &Node::displayCout;

int main() {
Node::useCout();
Node().test();

Node::useMessageBox();
Node().test();
}


However, I think you should really look into polymorphism, because it solves the exact same problem, but isn't nearly as complicated as working with pointers to class methods.

-Markus-

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this