Casey Patton
Casey Patton

Reputation: 4091

C++: Using function pointers with member functions

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.

Upvotes: 10

Views: 3123

Answers (2)

Dima
Dima

Reputation: 39389

As pointed out by others, your mistake is in the type of the function pointer being passed. It should be void (myClass::*passedFunction)().

Here is a good tutorial on using pointers to member functions in C++.

Upvotes: 1

john
john

Reputation: 87944

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::functionToPass is a pointer to a member function). They are not the same thing and they are not compatible.

You can rewrite your code like this

void myClass::function1(void (myClass::*passedFunction)())
{
   (this->*passedFunction)();
}

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.

Upvotes: 11

Related Questions