I'm making a game and the game works around a class I call Cyber_State. Every state of the game is a subclass of Cyber_State, for example the title screen you see when you start the game and the actual game.
Every state has a member that is a pointer to a Cyber_State. When a state is created this pointer points to itself, if you want to change states you build the next state and make next_state point to it. For example if you load a game from the main menu you make a new game(subclass of Cyber_State) based on a file and point next_state to it. The main loop then switches the state it works with at the end of the current iteration
Cyber_State.h
#include <Ogre.h>
#include <OIS/OIS.h>
#include <CEGUI/CEGUI.h>
#include <OgreCEGUIRenderer.h>
#include "Cyber_Util.h"
#include "ogreconsole.h"
class Cyber_State
{
protected:
Cyber_Kernel *kernel;
Cyber_State *transition;
public:
Cyber_State(Cyber_Kernel *kernel);
virtual bool frameStarted(const Ogre::FrameEvent& evt);
virtual bool frameEnded(const Ogre::FrameEvent& evt);
virtual bool keyPressed(const OIS::KeyEvent &arg);
virtual bool keyReleased(const OIS::KeyEvent &arg);
virtual bool mouseMoved(const OIS::MouseEvent &arg);
virtual bool mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id);
virtual bool mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id);
Cyber_State *next_state();
};
#endif
Cyber_State.cpp
#include "Cyber_State.h"
Cyber_State::Cyber_State(Cyber_Kernel *kernel){this->kernel = kernel; transition = this;}
bool Cyber_State::frameStarted(const Ogre::FrameEvent& evt){return true;}
bool Cyber_State::frameEnded(const Ogre::FrameEvent& evt){return true;}
bool Cyber_State::keyPressed(const OIS::KeyEvent &arg){return true;}
bool Cyber_State::keyReleased(const OIS::KeyEvent &arg){return true;}
bool Cyber_State::mouseMoved(const OIS::MouseEvent &arg){return true;}
bool Cyber_State::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id){return true;}
bool Cyber_State::mouseReleased(const OIS::MouseEvent &arg, OIS::MouseButtonID id){return true;}
Cyber_State *Cyber_State::next_state(){return transition;}
For an example in my game I run this function at the end of each frame
bool Cyber_Listener::frameEnded(const Ogre::FrameEvent& evt)
{
state->frameEnded(evt);
state = state->next_state();
if(state == NULL)
{
running = false;
}
return running;
}
My concern is this, what is the life span of a state returned by new_state? If I should delete the old state or it's memory gets freed automatically will the state returned by next_state be destroyed too? Or since Cyber_State only stores a pointer to to the next state will the next state itself be unharmed and accessible while I have a reference to it? While I'm at it does anyone have any links to help me understand memory in c++?