Sign in to follow this  

Pointers to functions

This topic is 4821 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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

This topic is 4821 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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