Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Reference to non-static member function must be called (2)

Tags:

c++

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?

like image 260
Abhishek Avatar asked Apr 01 '17 07:04

Abhishek


People also ask

What is a non static member function how is it called?

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)

How do you call a non static member function in C++?

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 error?

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.

How do you declare a static member function in C++?

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 ::.


1 Answers

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.

like image 157
AnT Avatar answered Nov 14 '22 23:11

AnT