Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 273
ashur Avatar asked May 27 '13 18:05

ashur


1 Answers

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);
          // ^                  ^
like image 95
jrok Avatar answered Oct 27 '22 01:10

jrok