I am trying to make a C++ Button class in which the user inputs a function to execute when the button is pressed. So far, this is my code:
class Button {
public:
char* text;
void* buttonclick();
Button (char* constext, void* consbuttonclick()) {
text = constext;
//What do I do here?
}
};
I am trying to make the constructor pass on the value of consbuttonclick() to buttonclick(). I believe there is a way to do this using function pointers, but I have been having trouble with them, so I would greatly appreciate some help on how to proceed.
What you’ve declared is a function returning a void *. You want a pointer to function returning void. So to start with you need to change the prototype: In place of
void * foo()you wantvoid (*foo)(). (You’ll have to sort out exactly what you want, but that’s the idea.)Once you have it, you call it simply by using the function invocation operator
(), so you’l get something likeBetter yet, though, is to create what’s called a functor class, like:
then pass a ClickFunctor object.
Now, go read the C++ FAQ book on these things. (Update: Marshall calls these things “functionoids” rather than “functors”, just to warn you.)