title: C++ Member function able to access data even it deleted the object that called it
body: <p>Here is a scenario I came across :- </p>
  
  <pre><code>#include &lt;iostream&gt;
  
  class Agent;
  class State;
  class OffState;
  class OnState;
  
  class State
  {
  public:
      virtual void execute(Agent * agent) = 0;
      virtual ~State() {std::cout &lt;&lt; "removing State\n";}
  };
  
  class Agent{
  
      State * currentState ; 
  public:
  
      Agent();
      void update(){
          std::cout &lt;&lt; "agent updating. will execute current State " &lt;&lt; std::endl;
          currentState-&gt;execute(this);
      }
  
      void changeState(State * newState){
          delete currentState;
          currentState = newState;
      }
  
  };
  
  class OffState : public State
  {
   public:
   ~OffState() {std::cout &lt;&lt; "deleting OffState Object" &lt;&lt;std::endl;}
      void execute(Agent * agent){
          std::cout &lt;&lt; "Nothing happens in the off State " &lt;&lt; std::endl;
      }
  };
  
  
  class OnState : public State
  {
  static int count ; 
  int id;
  public:
      OnState(){
          id = count;
          count++;
      }
  
      ~OnState() {std::cout &lt;&lt; "removing OnState id :- " &lt;id&lt;&lt;std::endl;}
  
          void execute(Agent * agent){
              std::cout &lt;&lt; "OnState executing" &lt;&lt; std::endl;
              agent-&gt;changeState(new OffState());  
              std::cout &lt;&lt; "executed after deleting OnState ? id:- " &lt;&lt; id  &lt;&lt; std::endl;
          }
  };
  int OnState::count = 0;
  
  Agent::Agent():currentState(new OnState()){ 
  }
  
  
  main(){
  
      Agent smith;
      smith.update();
  
  }
  </code></pre>
  
  <p>In this, the Agent's current state is initialised to an OnState object. This object is accessed via the update() method in Agent. This calls the OnState's execute method. Now this execute method indirectly deletes the OnState object which called it. Yet after that, control is passed back to the execute() method in the OnState object. What's more it is able to print the value of "id" . Shouldn't the memory pointed be deleted because of the delete currentState . </p>
  
  <p>Or is this the case where in some cases, the system may crash and in some cases, the memory contents wouldn't be immediately filled up by the operating system.  </p>
  
  <p>I thought that the function definition isn't stored in memory specific to instances as such, but this does not explain how the "id" value is still accessible.</p>
  
  <p>The output of the code was :-</p>
  
  <pre><code>agent updating. will execute current State 
  OnState executing
  removing OnState id :- 0
  removing State
  </code></pre>
  
  <p>executed after deleting OnState ? id:- 0</p>
  
  <p>Regards.</p>