Here is part of my code:
In a.h:
class classA
{
public:
void (*function_a)(void);
classA();
void function_a();
};
In a.cpp:
void classA::classA()
{
(*function_a)() = function_a;
}
void classA::function_a()
{
return;
}
I want to get function_a's address and save it into void (*function_a)(void), but I got compile error that "expression is not assignable". What shall I do to solve this problem?
First of all, choose different names for different things.
Second, the non-static member function pointer should be declared as:
void (classA::*memfun)(void); //note the syntax
then the assignment should be as:
memfun = &classA::function_a; //note &, and note the syntax on both sides.
and you call this as:
classA instance;
(instance.*memfun)();
That is what you do in C++03.
However, in C++11, you can use std::function
as well. Here is how you do it:
std::function<void(classA*)> memfun(&classA::function_a);
and you call this as:
classA instance;
memfun(&instance);
Online demo
To store a pointer to a class function you need something special, a pointer to a member. Here you can find a good explanation
In short, a member function can't be stored in a normal function pointer as it need to be handed a this pointer to the current class. A static member function works like a normal function as it need no this pointer.
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