Pointer to method

Asked

Viewed 199 times

1

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

The implementation of the method startAllegro class Application 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 pointer is the quitSwap, in routine set_close_button_callback.

set_close_button_callback is a routine of Allegro 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 the method startAllegro:

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

I’ve tried everything to solve but could not. Could someone more experienced in POO help me? Thanks

  • Um... maybe a casting of the solve function. Try to make the call like this: set_close_button_callback((void (*)(void)) quitSwap);

1 answer

2


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

The function is expecting something like void (*)(), then 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 hinting: the function you are passing is of the 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 roughly equivalent to:

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

Therefore it is not working. The function you are calling expects a function without parameters, but you are passing one with a parameter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.