Search code examples
c++pointersmethodsparameterspointer-to-member

How to call a C++ class method, which is given as a parameter?


I'm trying to pass a method as a parameter to other method.

Magner.h:

Class Manager{
public:
 timeCount(void (Manger::*function)(void));
void passedFuction();
}

In Manager.cpp, I'm trying to call timeCount by

timeCount(&Manager::passedFuction());

TimeCount Body:

void Manager::timeCount(void(Manager::*function)(void))
{
    std::cout << "It works";
    (*function)(); // here is error
}

ViusalStudio says:

void*Manager::*function)() operand of '*' must be a pointer

How should i correct it? The example i was learing by was : http://www.cplusplus.com/forum/beginner/6596/


Solution

  • A pointer-to-member-function (pmf) is not a pointer. Let me repeat that:

    A pointer-to-member-function is not a pointer.

    To call a pmf, you have to provide it with the object you want to call it on. You probably want:

        (this->*function)();
    

    If you had another object obj of the right type, you could also use:

        (obj.*function)();