State Machine Transitions

In this state machine implementation, the current state is represented by a function, and that function is stored in the m_state member variable. Switching states is therefore almost as simple as just updating this variable. Let’s wrap it in a function with a helpful name:

Recall that the dispatch() function simply forwards all events to the current state function. The new state function will receive all subsequently dispatched events. Continuing with our traffic light example, that means that CarEvents, for example, will continue to be dispatched, but now to our new state function.

It’s often useful to be able to do some additional work when entering or exiting a state. For example, a traffic light might might want to start a timer when entering a state which turns on the walk signal. This behavior can be added directly to the state functions by dispatching a couple of new events. Let’s define them first: