Using a member function pointer within a class

neuviemeporte picture neuviemeporte · May 24, 2010 · Viewed 15.4k times · Source

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?

Answer

fbrereto picture fbrereto · May 24, 2010

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);