16

I have this example code of using pointer to member function, which I want to change during runtime, but I cannot make it work. I've already tried this->*_currentPtr(4,5) (*this)._currentPtr(4, 5). What is the proper way of calling pointer to method inside same class ?

The error : expression must have (pointer-to-) function type

#include <iostream>
#include <cstdlib>

class A {

public:

    void setPtr(int v);
    void useFoo();

private:
    typedef int (A::*fooPtr)(int a, int b);

    fooPtr _currentPtr;

    int foo1(int a, int b);
    int foo2(int a, int b);
};

void A::setPtr(int v){
    if(v == 1){
        _currentPtr = foo1;
    } else {
        _currentPtr = foo2;
    }
}

void A::useFoo(){

    //std::cout << this->*_currentPtr(4,5); // ERROR
}

int A::foo1(int a, int b){
    return a - b;
}

int A::foo2(int a, int b){
    return a + b;
}

int main(){

    A obj;

    obj.setPtr(1);
    obj.useFoo();

    return 0;
}
szym
  • 5,606
  • 28
  • 34
ashur
  • 4,177
  • 14
  • 53
  • 85

1 Answers1

23

You need to tell the compiler which class the foos are coming from (otherwise it thinks they're functions from global scope):

void A::setPtr(int v){
    if(v == 1){
        _currentPtr = &A::foo1;
                  //  ^^^^
    } else {
        _currentPtr = &A::foo2;
                  //  ^^^^
    }
}

and you need a set of parentheses here:

std::cout << (this->*_currentPtr)(4,5);
          // ^                  ^
jrok
  • 54,456
  • 9
  • 109
  • 141
  • 1
    Thanks that helped me. But I'm confused why is there need for `&` operator, I thought that function is treated as address. – ashur May 27 '13 at 18:28
  • 2
    @ashur That's true for normal functions, but not for member functions. And the latter are not regular pointers. – jrok May 27 '13 at 18:39
  • 2
    @ashur See [this article](http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible) for an interesting read about ins and outs of member pointers. – jrok May 27 '13 at 18:45