Sunday, 19 July 2020

Creating a state Machine in C++ using virtual function


                                    Creating a State Machine in C++ using virtual function

 We can create a state machine using virtual function , instead of normal pointer function which is using index to jump to a function, we are using Object of that particular class(which represent state) to jump to the particular run() function of that class.

Here signal maps to the class object and triggers run() function of that class object.
We are using concept of Runtime Polymorphism instead of compile time polymorphism.

class StateMachine
{
public:
    int signal;
    void print ()
    { cout<< "print base class" <<endl; }
  
    virtual void run ()
    { cout<< "show base class" <<endl; }
};
  
class Init_State:public StateMachine
{
public:
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
    { cout<< "print derived class" <<endl; }
  
    void run ()
    { cout<< "We are in init state" <<endl; }
};
class Run_State:public StateMachine
{
public:
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
    { cout<< "print derived class" <<endl; }
  
    void run () 
    { cout<< "we are in running state" <<endl; }
};
class DeInit_State:public StateMachine  
{
public:
    void print () //print () is already virtual function in derived class, we could also declared as virtual void print () explicitly
    { cout<< "print derived class" <<endl; }
 
    void run ()
    { cout<< "we are in deinit state" <<endl; }
};
 
 
//run the State Machine function
void runStateMachine(void *p)
{
    StateMachine *ptr = (StateMachine *)p;
      switch(ptr->signal)
     {
       case 0:
       ptr = new Init_State;
       break;
       case 1:
       ptr = new Run_State;
       break;
       case 2:
       ptr = new DeInit_State;
       break;
     }
    //Non-virtual function, binded at compile time
    ptr->print(); 
      
    // virtual function, binded at runtime (Runtime polymorphism)
    ptr->run(); 
 
    return;
}

int main()
{
   StateMachine *ptr = new StateMachine;
   ptr->signal = 0;  // controls the state
   runStateMachine((void*)ptr);
}