TITLE: Interesting finite-state-machine template [ This material from "C++ Report", Feb 95, p. 24 by James Coplien ] Here is an interesting snippet of code taken from the above source. It is unusual in that the user's code is sandwiched between an abstract base and a template derived class. Here is the client side of the code: class myFSM : public BaseFSM { public: void x1 (char); void x2 (char); void init () { addState (1); addState (2); addTransition (EOF, 1, 2, &myFSM::x1); ...; } }; int main () { FSM myMachine; ...; } Here is the code for both the abstract base class and the derived fsm. The unusual thing to note here is that the user fsm passes its class up to the abstract fsm AND that the common methods and data are located in the derived fsm not the base! template class baseFSM { public: virtual void addState (State) = 0; virtual void addTransition (Stimulus, State, State, void (M::*)(Stimulus)) = 0; virtual void fire (Stimulus) = 0; }; template class FSM : public UserMachine { public: FSM () { init (); } virtual void addState (State); virtual void addTransition (Stimulus, State from, State to, void (UserMachine::*) (Stimulus)); virtual void fire (Stimulus); private: State nstates, *states, currentState; Map *transitionMap; }; Why would we put common stuff in a derived class rather than a base? - "the fsm should initialize itself without the user explicitly calling init" - "a constructor should orchestrate the initialization" - "because init references virtual functions, it should not be called until after myFSM constructor completes (so the virtual function dispatching works)" - "therefore, init cannot be called from the constructor for myFSM or any of its base classes" - "we want the create only as many classes as necessary" For a detailed explaination see the article cited above.