Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference to non-static member function must be called

I'm using C++ (not C++11). I need to make a pointer to a function inside a class. I try to do following:

void MyClass::buttonClickedEvent( int buttonId ) {     // I need to have an access to all members of MyClass's class }  void MyClass::setEvent() {      void ( *func ) ( int );      func = buttonClickedEvent; // <-- Reference to non static member function must be called  }  setEvent(); 

But there's an error: "Reference to non static member function must be called". What should I do to make a pointer to a member of MyClass?

like image 962
JavaRunner Avatar asked Oct 13 '14 01:10

JavaRunner


People also ask

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

A non- static member function is a class / struct / union member function, which is called on a particular instance, and operates on said instance. Unlike static member functions, it cannot be called without specifying an instance. For information on classes, structures, and unions, please see the parent topic.

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 is static and non-static member function?

A static member function can be called, even when a class is not instantiated. A static member function cannot have access to the this pointer of the class. A non-static member function can be declared as virtual but care must be taken not to declare a static member function as virtual.

What is a non-static member object?

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)


1 Answers

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int); func = &MyClass::buttonClickedEvent; 

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>); 

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

like image 78
imreal Avatar answered Sep 19 '22 01:09

imreal