ashur ashur - 3 months ago 7
C++ Question

C++: Calling member function via pointer

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

Answer

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