Pointer to method

1

I started studying object orientation and I'm trying to call pointer to method, but I'm having trouble.

The implementation of the startAllegro method of the Application class is as follows:

void Application::startAllegro(){
    allegro_init();
    install_timer();
    install_keyboard();
    set_color_depth(32);
    set_gfx_mode(GFX_AUTODETECT_WINDOWED, width, heigth, 0, 0);
    set_window_title(&name[0]);
    set_close_button_callback(quitSwap);
}

The other method I'm trying to pass as a pointer is quitSwap , in the set_close_button_callback routine.

set_close_button_callback is an allegro routine and has the following prototype: set_close_button_callback(void (*proc)(void));

The implementation I made of the quitSwap method is:

void Application::quitSwap(){
    quit = true;
}

I'm getting the following error in method startAllegro :

application.cpp:20: error: argument of type 'void (Application::)()' does not match 'void (*)()'

I have tried everything to solve, but I could not. Anyone more experienced in OOP could help me? Thanks

    
asked by anonymous 12.06.2015 / 10:45

1 answer

2

I have no experience with Allegro, but what you are trying to do is not going to work because you are passing a pointer to member function when expected is a pointer to free function.

The function is expecting something of type void (*)() , so you could have something like this:

void quit_handler() { ... }

//...

set_close_button_callback(quit_handler);

But you are trying to pass a member function. The error message is already giving the hint: the function you are passing is of type void (Application::*)() . C ++ differentiates free function pointers and member function pointers because they have the hidden parameter this .

void Application::quitSwap(){
    quit = true;
}

is more or less equivalent to:

void Application_quitSwap(Application *this){
    this->quit = true;
}

So it's not working. The function you are calling expects a function with no parameters, but you are passing one with a parameter.

    
12.06.2015 / 15:09