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.
The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.
Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);
Which is the pointer which denotes the object calling the member function? Explanation: The pointer which denotes the object calling the member function is known as this pointer. The this pointer is usually used when there are members in the function with same name as those of the class members.
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.
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++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With