I'm working on a Pacman game in C++, but have run into a problem with member function pointers. I have 2 classes, pacman
and ghost
, that both inherit from Mouvement
. In the subclasses, I need to pass a function to a function in Mouvement
. However, I can't simply have static functions as then I would need static variables, which would not work.
I have tried passing &this->movingUp
which throws the error 'Cannot create a non-constant pointer to member function'
I have tried passing &<ghost or pacman>::movingUp
which throws the error "Cannot initialize a parameter of type 'void ()(int)' with an rvalue of type 'void (::)(int)' "
Here's what's relevent: (I cut out most of it, so that you only see what's necessary for this problem)
class cMouvement {
protected:
int curDirection = -3; // Variables that are used in the 'movingUp, etc' functions.
int newDirection = -3; // And therefore can't be static
public:
void checkIntersection(void (*function)(int), bool shouldDebug){
// Whole bunch of 'If's that call the passed function with different arguments
}
And then class pacman
and ghost
, which are very similar at this point.
class pacman : public cMouvement {
void movingUp(int type){
// Blah blah blah
}
// movingDown, movingLeft, movingRight... (Removed for the reader's sake)
public:
/*Constructor function*/
void move(bool shouldDebug){
if (curDirection == 0) {checkIntersection(&movingUp, false);}
else if (curDirection == 1) {checkIntersection(&movingRight, false);}
else if (curDirection == 2) {checkIntersection(&movingDown, false);}
else if (curDirection == 3) {checkIntersection(&movingLeft, false);}
}
};