Modeling a Generic State
Let’s look at how to model a state using C++ code. Listing 2 illustrates a basic state class.
Listing 2 The state class
State::State() { } char* State::whatCanWeDo(void) { return "Nothing"; } void State::ChangeState(EngineEntity* enginePtr, State* statePtr) { enginePtr->changeState(statePtr); }
The State class is the base class that is used by all derived state classes. This class provides one public member function called whatCanWeDo() that enables us to determine the capabilities of the container state. (You’ll see the use of this method later on.)
Notice the use of a protected constructor (in the header file State.h) for the use of derived subclasses. Another protected member function ChangeState()(also in the header file State.h) allows the state to be changed. As for the constructor, ChangeState() is intended to be overridden by subclasses.
Let’s now create a subclass of State.