Search code examples
c++classfunction-pointerspointer-to-member

How do I call pointer-to-member functions from another class?


I have two classes, Button and Game. The Game class contains members of type Button*, and the Button class contains a pointer to a member function in the Game class.

class Game{
    public:
        Button* button1;

        void init();
        void tick();

        void wantetEvent();
};

class Button{
    public:
        void (Game::*click)();
};

I now define the click function pointer in the init function of Game.

void Game::init(){
    button1 = new Button;
    button1->click = &Game::wantetEvent;
}

In the tick function I want to call the click function of button1. Here's what I've tried so far:

void Game::tick(){
    (button1->*click)();
    (button1->*Game::click)();
}

There are lots of other things I tried, but they were less promising than these examples. The issue is that the compiler tell me that 'click' was not declared in this scope on the first example and 'click' is not a member of 'Game' in the second one. Is the issue that I'm trying to access a function that - from the pointers perspective - is in another class? Or is there some solution that allows me to call the function in such a way?


Solution

  • You need an instance to call it:

    void Game::tick(){
        (this->*(button1->click))();
    }
    

    Demo