58

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?

imreal
  • 10,178
  • 2
  • 32
  • 48
JavaRunner
  • 2,455
  • 5
  • 38
  • 52
  • 4
    You can't have a function pointer assigned to a member function. You either have to use a pointer to member, or a free function. – imreal Oct 13 '14 at 01:16
  • What do you mean by the "pointer to a member"? As for "free function" you meant a function outside a class? Yeah, I know that it will work if I'll remove "MyClass::" part from definition "void MyClass::buttonClickedEvent..." but I need to have an access to members of MyClass inside the function "buttonClickedEvent"... – JavaRunner Oct 13 '14 at 01:26

3 Answers3

64

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

imreal
  • 10,178
  • 2
  • 32
  • 48
  • 4
    By the way, when I call this->*func(23) - it doesn't work because I need to use it with parentheses like this: (this->*func)(23) – JavaRunner Oct 13 '14 at 11:32
19

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

lepe
  • 24,677
  • 9
  • 99
  • 108
xiaodong
  • 952
  • 1
  • 7
  • 19
0

you only need to add parentheses after the function call and pass arguments if needed

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 30 '23 at 14:38