Search code examples
c++pointer-to-member

Using a member function pointer within a class


Given an example class:

class Fred
{
public:
Fred() 
{
    func = &Fred::fa;
}

void run()
{
     int foo, bar;
     *func(foo,bar);
}

double fa(int x, int y);
double fb(int x, int y);

private:
double (Fred::*func)(int x, int y);
};

I get a compiler error at the line calling the member function through the pointer "*func(foo,bar)", saying: "term does not evaluate to a function taking 2 arguments". What am I doing wrong?


Solution

  • The syntax you need looks like:

    ((object).*(ptrToMember)) 
    

    So your call would be:

    ((*this).*(func))(foo, bar);
    

    I believe an alternate syntax would be:

    (this->*func)(foo, bar);