0

I have an array that contains function pointers to functions that are inside my GameBoard class. How can I call one of those functions?

class myClass {
    int plusOne(int val) {return val + 1;}
    int minusOne(int val) {return val - 1;}
    int keepTheSame(int val) {return val;}

    int (myClass::*functions[3])(int val) {&myClass::plusOne, &myClass::minusOne, &myClass::keepTheSame};

    // Get coordinates of all positions that flip when placing disc at x,y
    vector<pair<int, int>> getFlipDiscs(pair<int, int> moveCoord, int color) {
        int a = (*functions[0])(2); // error: indirection requires pointer operand
    }
};

I've looked on the internet for member function pointers and arrays of function pointers and found quite a lot of information, but I wasn't able to combine those in a working solution.

2 Answers 2

4

Your function pointers are actually pointer to member functionss. To call any of these you’ll need to provide the object of the class you want to call them on. I think this should work:

(this->*(functions[0]))(2);

That said, I recommend not to pursue this direction! Sooner or later you’ll want to register other operations and usin an array of std::function<Signature> objects is more flexible.

Sign up to request clarification or add additional context in comments.

Comments

0

Don't you complicate it too much? How about this one:

#include <stdio.h>

int plusOne(int val) {return val + 1;}
int minusOne(int val) {return val - 1;}
int keepTheSame(int val) {return val;}

int (*functions[3])(int val) {plusOne, minusOne, keepTheSame};

int main()
{
    int a = (functions[1])(2); // no error
    printf("%d\n", a);
}

3 Comments

It gives the error: 'Reference to non-static member function must be called'. Remember the code I gave is inside the GameBoard class, as noted in the question. Therefore these three functions are member functions.
I updated the question to better match the situation
Yes, this code only works as is, not inside the class. Maybe if the functions are simple and generic enough, one can keep them outside of a class as C++ is not strictly object-oriented. But Dietmar's magic solution seems to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.