title: Arduino class destructor called while object is still in scope
body: <p>I'm working on a small class for the ESP8266 and I need to be able to hold a reference to an object in another instance of the same object. When running the code I've been getting Exceptions. After some debugging it looks like the class destructor is called while the object is still in scope. I've not worked with C++ for a long time but this behavior seems wrong.  </p>
  
  <p>There are really two questions.</p>
  
  <ol>
  <li>Why is the destructor called when the object is still in scope?</li>
  <li>Is it possible to hold a reference to the object past the scope of the object without the destructor being called (as in a linked list)?</li>
  </ol>
  
  <p>I've reduced the code to a small program that shows the issue. In the code below the class destructor is called on the 'child' object while it's still in scope. It's actually called twice as I point out in the code. </p>
  
  <p>Here's the output from the code:</p>
  
  <pre>
          Starting
          adding child to root
          Out of scope name=child
          adding child to root2
          Out of scope name=child
          Done, both root and child should still be in scope
  </pre>
  
  <pre><code>#include "Arduino.h"
  
  class TestObject {
      private:
         char name[20];
         TestObject* child;
  
      public:
         TestObject(const char* name);
         virtual ~TestObject();
         void setChild(TestObject h) ;
         char *getName();
  };
  
  TestObject::TestObject(const char *name) {
      child = (TestObject*)0;
      strcpy(this-&gt;name,name);
  }
  
  TestObject::~TestObject() {
      Serial.println("Out of scope name="+String(name));
  }
  
  char *TestObject::getName() {
      return name;
  }
  
  void TestObject::setChild(TestObject h ) {
      child = &amp;h;
      Serial.println("adding "+String(h.name)+" to "+String(name));
  }
  
  void setup() {
    Serial.begin(115200);
    delay(1000);
    Serial.println("\nStarting");
    TestObject root = TestObject("root");
    TestObject child = TestObject("child");
    root.setChild(child); // child destructor is called here but it should still be in scope
    delay(1000);
    TestObject root2 = TestObject("root2");
    root2.setChild(child);// child destructor is called a second time here
    Serial.println("Done, both root and child should still be in scope");
    while(true) {
      delay(10000);
    }
  }
  </code></pre>