I have a piece of code like this
class A {
public:
typedef int (A::*AFn)(int);
std::map<std::string, AFn> fm_;
A() {
fm_.insert("fn1", fn);
}
int fn(int a) {
return a;
}
};
I get a compile time error saying error: reference to non-static member function must be called
fm_.insert("fn1", fn);
Why does this happen and how do I correct it?
A non-static member function is a function that is declared in a member specification of a class without a static or friend specifier. ( see static member functions and friend declaration for the effect of those keywords)
A class can have non-static member functions, which operate on individual instances of the class. class CL { public: void member_function() {} }; These functions are called on an instance of the class, like so: CL instance; instance.
What happens if non static members are used in static member function? Explanation: There must be specific memory space allocated for the data members before the static member functions uses them. But the space is not reserved if object is not declared.
Static Function Members By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.
Since fn
is a non-static member function, a lone fn
is not a valid expression. The only thing you can do with non-qualified fn
in this context is call it: fn(something)
. This is what the compiler is telling you.
If you want to obtain a pointer to member function A::fn
, you have to explcitly use operator &
and supply a qualified member name: &A::fn
.
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