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.
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.