I’m trying to pass a function to another function as a parameter, and they both happen to be member functions of the same class.
I’m getting a weird error and I can’t figure out what the problem is.
Here are my functions:
void myClass::functionToPass()
{
// does something
}
void myClass::function1(void (*passedFunction)())
{
(*passedFunction)();
}
void myClass::function2()
{
function1( &myClass::functionToPass );
}
However, I’m getting the following error:
cannot convert parameter 1 from 'void(__thiscall myClass::*) (void)'
to 'void(__cdecl*)(void)'
So what gives? I feel like I’ve tried every variation to try to get this to work. Can you even pass function pointers for member functions? How can I get this to work?
Note: Making functionToPass static isn’t really a valid option.
You can pass function pointers to member functions. But that is not what your code is doing. You are confused between regular function pointers (
void (*passedFunction)()is a regular function pointer) and pointers to member functions (&myClass::functionToPassis a pointer to a member function). They are not the same thing and they are not compatible.You can rewrite your code like this
Now your code is using pointers to member functions, but of course this means you won’t be able to pass a regular function pointer.