• C++ Member-Pointers – games assignment

    Adelaid Member

    Hey guys, so I’m in the middle of completing my C++ games assignment and I’ve ran into a pretty decent problem I can’t solve.

    The game is complete but the problem comes with coding the menu system and the buttons.

    My button class is pretty basic, it holds a texture, position and a function to point to when clicked.

    void (*m_action)();

    Now the problem I’ve ran into is, that works but only for functions declared inside the main method and not inside any other class.

    I’m working with a


    The main class holds the game class and the game class holds the button class.

    The problem I’ve ran into is sending the button a pointer to a Game::*function rather just a *function.

    I’ve tried many things to get this to work but still can’t get the button to hold a member pointer to function inside the game class.

    If anyone could help I’d be eternally grateful!

  • Amit Member

    I’m not sure what do you mean by ‘game class holds the button class.’, let’s suppose this means: ‘game class holds instance of a button class’ (not declaration of this class). In this case simple-sample can look like this (tested in vs2010):

    class Button;
    class Game
       Button button;
       public:   //Function must be public, otherwise it will be impossible do something like this: "Game::Add" outside class Game!
          float Add(float x, float y) { return x + y; }
    class Button
       float (Game::*pt2mfn)(float x, float y);
          pt2mfn = &Game::Add;
    int _tmain(int argc, _TCHAR* argv[])
       Button btn;
       Game game;
       //Naturally we will need instance of Game class to call nonstatic, member method!
       std::cout<< (game.*btn.pt2mfn)(1.0f, 1.0f) << std::endl;
       return 0;
  • SapnaVishwas Member

    Have a look at boost::function and boost::bind, they may be helpful.

Viewing 2 reply threads
  • You must be logged in to reply to this topic.