0

I'm pretty new to C++ (after many Java years). I'm trying to use a function pointer to a member function of my class like this:

class MyClass
{
public:
    MyClass();
    void foo();
    void bar();
};

MyClass::MyClass(){}

void MyClass::bar(){}


void MyClass::foo()
{
    void (MyClass::*myMethod)();
    myMethod = &MyClass::bar;

//-----THIS IS THE LINE WITH PROBLEM-----------
    myMethod();

}

However, the compiler fails:

test.cpp: In member function ‘void MyClass::foo()’:
test.cpp:22:14: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘myMethod (...)’, e.g. ‘(... ->* myMethod) (...)’
     myMethod();
          ^

I've been trying various mix of *, & characters, and googled for solutions, but cannot get it to work.

Any idea?

gpo
  • 3,388
  • 3
  • 31
  • 53
  • 2
    Paste "how to call member function pointer C++" into google. Today must be your lucky day, because it's the first result! – Bartek Banachewicz Oct 08 '15 at 10:34
  • The error message literally tells you what to do... did you at any stage consider reading it? – Lightness Races in Orbit Oct 08 '15 at 10:56
  • 1
    Wow, guys, why the agressivity? Yes I read the error message, and Yes I googled it. Sorry but the correct result is the accepted answer below, and it is NOT the same as the answer that this questions has been marked duplictated of. The other answer is: (bigCat.*pcat)(); This answer is: (this->*myMethod)(); There are subtle differences ("." instead of "->" and "this" instead of actual variable name). Those subtle differences are hard to spot for a C++ newbie like me. Hence posting here. – gpo Oct 08 '15 at 11:08

1 Answers1

6

myMethod is a member function, so you need to call it on an instance of the class it is a member of. Since you are already in a member function, you can use this:

(this->*myMethod)()
TartanLlama
  • 63,752
  • 13
  • 157
  • 193