Jump to content
  • Advertisement
Sign in to follow this  
Hermes

Pointers to functions

This topic is 5015 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!