0

Set function for an instance of a class

Hello ! I am currently working on a UI tool in C++ using SDL2 (already made one in Python with OOP and Pygame). I want to make buttons which each has a custom function named "click_event". I want to pass this function as an argument in the constructor "Button", but it gives me an error... class Button{ int x, y; int width, height; void click_event(); [...] public : Button(int x, [...], void (*click_event)()){ this->x = x; [...] this->click_event = *click_event; // This gives me an error [*] } [...] }; [*] : error: invalid use of member 'void Button::click_event()' (did you forget the '&' ?) void (*click_event)() is a pointer to the function, right ? So, *click_event is the function ? Please correct me if I'm wrong... Have a good day !

18th Jul 2022, 8:10 AM
Arthur Le Floch
3 Réponses
+ 2
I don't think you need void there twice. In your 4th line you have "void click_event();", so leave out the void in line 7. See if that works.
18th Jul 2022, 8:24 AM
Ausgrindtube
Ausgrindtube - avatar
0
The line 7 defines a function, so i'm pretty sure we need to specify the type for every arguments. I also tried, it doesn't work :/
18th Jul 2022, 8:31 AM
Arthur Le Floch
0
I found a solution ! (which I don't fully understand though... If someone could explain me I would be grateful !) class Button{ int x, y; int width, height; void (*click_event)(); // changed, I don't really understand what's happening here [...] public : Button(int x, [...], void click_event()){ // changed this->x = x; [...] this->click_event = click_event; // changed } [...] }; I also found out we can use click_event without any 'decorations' around such as '&' or '*' (as a classic function).
18th Jul 2022, 3:44 PM
Arthur Le Floch