Using OOP! Make a class such as 'GameState' and make other states that inherit this, such as 'Menu', 'InGame' and whatever else. How you handle the rest really depends on what coding patterns you like, but one method would be to make the base 'GameState' class maintain a pointer to the current game state that's set via a static variable and in its constructor you would check to see if this variable is already set, if so, then delete that. This will ensure that only one 'GameState' instance is active at any time, and it allows you to easily switch between them by simply doing: new Menu(); example(untested):
class GameState
{
public:
static void remove()
{
delete currentState;
}
static void update()
{
if ( currentState )
currentState->update_impl();
}
protected:
GameState()
{
remove();
currentState = this;
}
virtual ~GameState()
{
currentState = nullptr;
}
virtual void update_impl() = 0;
private:
static GameState* currentState;
};
GameState* GameState::currentState = nullptr;
class InGame
: public GameState
{
public:
InGame(){};
~InGame(){};
protected:
virtual void update_impl()
{
}
};
class Menu
: public GameState
{
public:
Menu(){};
~Menu(){};
protected:
virtual void update_impl()
{
new InGame(); // Go in game
}
};
int main()
{
new Menu();
for (;;)
{
GameState::update();
}
GameState::remove();
}
Or using templates for nicer syntax:
class GameState
{
public:
static void remove()
{
delete currentState;
}
static void update()
{
if ( currentState )
currentState->update_impl();
}
template <class T>
static void switchTo()
{
// Ensure only GameStates are passed
static_cast<GameState*>( new T() );
}
protected:
GameState()
{
remove();
currentState = this;
}
virtual ~GameState()
{
currentState = nullptr;
}
virtual void update_impl() = 0;
private:
static GameState* currentState;
};
GameState* GameState::currentState = nullptr;
class InGame
: public GameState
{
public:
InGame(){};
~InGame(){};
protected:
virtual void update_impl()
{
}
};
class Menu
: public GameState
{
public:
Menu(){};
~Menu(){};
protected:
virtual void update_impl()
{
GameState::switchTo<InGame>();
}
};
int main()
{
GameState::switchTo<Menu>();
for (;;)
{
GameState::update();
}
GameState::remove();
}
Note: This code is unsafe, in that switching states within a game state's method is effectively the same as 'delete this;', so you wouldn't want to access any class variables after switching states, or you could improve it so the class is only deallocated once the derived functions have returned.