function pointer problem.

I have created a game with three different “levels”, i.e. three different game algorithms. The algorithms are defined in testApp.cpp in three separate functions, gameOne(), gameTwo(), gameThree(). What I’m trying to do is to create a function pointer named currentGame, which is called in testApp::update(), and points to the different game functions as the game runs along.

I have declared the functions and pointer as follows:

  
class testApp : public ofBaseApp   
{  
	public:  
		void gameOne();  
		void gameTwo();  
		void gameThree();  
  
  
	private:  
		void *currentGame();  
  
};  
  

And in testApp::setup() I have written:

  
currentGame = &gameOne();  

This however renders the error message:
error: non-lvalue in unary `&’

I’m not that at home with function pointers, and I have tried a couple of variants on the initialization but nothing works.

IN c++ function pointers do not work as expected. You need two variables, to call a function in an object, the object instance and the pointer to the function, as the function is part of a specific object. (Do a google-search for functors in c++ if you are interested)

So, to get your code working:

  
class testApp : public ofBaseApp   
{  
	public:  
		void gameOne();  
		void gameTwo();  
		void gameThree();  
  
  
	private:  
		void (testApp::*currentGame)(); // this stores the pointer to the function  
  
};  
  

  
currentGame = &testapp::gameOne;  

to call the function you simply do

  
  
 (*this.*currentGame)();  
  

but why don’t you embed your games into separate classes all inheriting from a base-class defining the interface for all games?

cheers,
Stephan

coming from Java, I’m new to the whole concept of pointers, so I’m just trying to get a grip of it, maybe I’ll make a base game class later on.

the syntax doesn’t feel very intuitive, but as long as it works… thanks alot for the help!