Search code examples
c++pointer-to-member

Class member function pointer as a class member


// class
class MyClass
{
public:
void doIt() const
{
    cout << "It works!" << endl;
}

void(MyClass::*fPtr)() const;
};

// main

MyClass *t = new MyClass;

// store function address
t->fPtr = &MyClass::doIt;

(*(t->fPtr))(); // Whats wrong with this line?

How can i call the function stored in fPtr? when i try (*(t->fPtr))(); compiler gives those errors :

error C2171: '*' : illegal on operands of type 'void (__thiscall MyClass::* )(void) const

error C2064: term does not evaluate to a function taking 0 arguments


Solution

  • (*(t->fPtr))(); is wrong, thre right syntax is ((object)->*(ptrToMember))

    means

    (t->*(t->fPtr))();
    

    More background info here: http://www.parashift.com/c++-faq-lite/pointers-to-members.html (But better ignore these macros from that page..)