Thanks, but I already know what a function pointer is and how to use them when there in scope. But how do you use them when they are out of scope like in the sample code I posted?
You can't just toss the function in the class as that makes it dynamic and makes the pointers invalid.
class MyType
{
private:
void(*callback)(int, void*);
public:
// the function must be in scope when this is called
void set_callback(void(*func_ptr)(int, void*))
{
callback = func_ptr;
}
// the original function does not have to be in scope when this is called
// because its pointer is stored in the internal scope of the object.
void do_stuff()
{
callback(7, 0);
}
};
// ...
void testfunc(int i, void* v)
{
// ...
}
int main()
{
MyType mytype;
mytype.set_callback(&testfunc);
// ...
}
You would use a function pointer if you need to call one function or the other (or others) depending on the functionality that you want. If you only have a single function, meaning there is only one choice of function, why bother with a function pointer? That would be nonsense, yes. But since I am failing to understand the full picture here, I can't be sure this is what you want/are doing.
In situations where it doesn't make sense, then don't do it. In fact I would recommend that you avoid function pointers completely if at all possible. However if you are forced to, or for some reason it does make sense, you now know how to do it.
In your particular case you need to give us more information on what you are trying to do in order for us to suggest a better solution.
Well I'm using the wxWidgets library and I'm trying to bind events using the bind function. The bind function requires a pointer to a function in order to call it when an event happens. The class' constructor registers the event with the bind event.
I have a function supplied which handles the event for the user. I would like the class to just register the event and use the supplied event handling function without the user needing to manually specify it in their code.