10

I want to call member-functions through member-function-pointers. The calling function is also a member.

class A;

typedef int (A::*memFun)();

class A
{
    int P(){return 1;}
    int Q(){return 2;}
    int R(){return 3;}

    int Z(memFun f1, memFun f2)
    {
        return f1() + f2(); //HERE
    }
public: 
    int run();
};

int A::run()
{
    return Z(P, Q);
}

int main()
{
    A a;
    cout << a.run() << endl;
}

I am not doing it correctly, and am getting error-

main.cpp:15:19: error: must use '.*' or '->*' to call pointer-to-member function in 'f1 (...)', e.g. '(... ->* f1) (...)'
         return f1() + f2(); //HERE

Please show the correct way to do it.

EDIT - there is another error, which is solved by having-

return Z(&A::P, &A::Q);
Vinayak Garg
  • 6,518
  • 10
  • 53
  • 80

4 Answers4

18
(this->*f1)() + (this->*f2)();

Regardless of whether you're calling it from inside the class, you have to explicitly specify the object on which to call (in this case this). Also note the required parentheses. The following is wrong:

this->*f1() + this->*f2()
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
  • +1 Thanks, that works. I did try `this->*f1() + this->*f2()` after seeing compiler error, but ofcourse it didn't work. – Vinayak Garg Apr 29 '13 at 10:43
4

Like this:

(this->*f1)() + (this->*f2)()
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

While you don't show it, you most likely have errors when calling Z as well.

You need to call the function like this:

Z(&A::P, &A::Q)
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

you have to use this

(this->*f1)(); 
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
stardust
  • 5,918
  • 1
  • 18
  • 20