Reference to non-static member function must be called

C++PointersReference

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

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

Solution 2 - C++

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJavaRunnerView Question on Stackoverflow
Solution 1 - C++imrealView Answer on Stackoverflow
Solution 2 - C++xiaodongView Answer on Stackoverflow