13

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?

neuviemeporte
  • 6,310
  • 10
  • 49
  • 78

6 Answers6

25

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);
fbrereto
  • 35,429
  • 19
  • 126
  • 178
8

You need the following funky syntax to call member functions through a pointer:

(this->*func)(foo, bar);
Thomas
  • 174,939
  • 50
  • 355
  • 478
7

There are two things you need to take care of. First is the declaration of the function pointer type:

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

Next is the syntax for calling the function using a pointer:

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

Here is the modified sample code that will compile and run:

#include <iostream>

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

  void run()
  {
    int foo = 10, bar = 20;
    std::cout << (this->*func)(foo,bar) << '\n';
  }

  double fa(int x, int y)
  {
    return (double)(x + y);
  }
  double fb(int x, int y)
  {
  }

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

int
main ()
{
  Fred f;
  f.run();
  return 0;
}
Vijay Mathew
  • 26,737
  • 4
  • 62
  • 93
2

Non static class member functions have hidden this pointer as an argument.

I think, the syntax (this->*func)(foo,bar) is the way to make compiler understand that it need to add this to the function.

Learner
  • 597
  • 1
  • 5
  • 17
1

A member function with two args is really a three arg function. 'this' is an implicit argument so the error you are getting is about missing the 'this' arg.

stonemetal
  • 6,111
  • 23
  • 25
0

A complete example can be

#include <iostream>

using namespace std;

class Fred
{
public:
void run()
{
    int foo=1, bar=2;

    func = &Fred::fa; 
    cout << "Function A: " << (this->*func)(foo,bar) << endl;

    func = &Fred::fb;
    cout << "Function B: " << (this->*func)(foo,bar) << endl;
}

private:
double fa(const int x, const int y) {return x + y;}
double fb(const int x, const int y) {return x * y;}

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

int main()
{
    Fred objFred;
    objFred.run();
    return 0;
}
raz
  • 482
  • 1
  • 5
  • 17