How do you implement a state machine in an object oriented way? The book Game Programming Patterns has a good chapter on that. At work we use a similar pattern in automotive. Compared to game programming, we are more paranoid since we steer a ton of metal at 100km/h for real. There is one aspect about Robert Nystroms pattern which I would do differently.

Avoid input parameters Nystrom considers game programming and his example state machine is concerned with the animation and movement of the players character, a heroine. This is the interface for the heroines state: class HeroineState { public : virtual void handleInput ( Heroine & heroine , Input input ) {} virtual void update ( Heroine & heroine ) {} }; I propose the following change that handleInput returns a state instead of modifying a Heroine parameter. class HeroineState { public : virtual HeroineState * handleInput ( Input input ) {} virtual void update ( Heroine & heroine ) {} }; This has two advantages: handleInput can only rely on the inputs and not on the state of the Heroine. In Game Programming Patterns handleInput calls setGraphics . Such transition effects are better done in the update method and decoupled from the state transitions.

. Such transition effects are better done in the update method and decoupled from the state transitions. No aliasing. In Nystroms version of HeroineState::handleInput the this pointer aliases with the current state in Heroine . Our static analysis does not like that. To use the state machine, it must be attached to the actual Heroine class. For example as member called state_ . In the Heroine class we can add entry and exit actions in a generic way. class Heroine { public : virtual void handleInput ( Input input ) { auto next = state_ -> handleInput ( input ); if ( next != state_ ) { state_ -> onExit ( * this ); next -> onEntry ( * this ); state_ = next ; } } }; Nystrom already describes that entry/exit pattern but does not take the next step to remove the heroine parameter. Of course, you can pass additional parameters to handleInput to explicitly allow state transitions based on additional inputs. You might even pass in the heroine object, but at least you can now make it const .