title: C++ How to delete a default object member which is a pointer
body: <p>I have a type which has as a member a pointer to another object. When the object (Demo) is created, it initializes the other object (Property) in the constructor. I figure if I have a lot of these objects, I wouldn't want to waste heap space when I change property to something differently, so I free the initialized memory in <code>setProperty</code>, then in the Demo's deconstrucor I delete it again, since it will have been set to something different by that point. However, this causes the code to crash. Why does it crash if I'm reassigning <code>property</code> when it is reset?  </p>
  
  <pre><code>class Property{ };
  
  
  class Demo{
      protected:
              Property *property;
      public:
              Demo(){ property = new Property();};
  
              void setProperty(Property *p){
                      delete property;
                      property = p;
              };
  
              ~Demo(){
                      delete property;
              };
  };
  
  int main(){
      Property p = Property();
      Demo * d = new Demo();
  
      d-&gt;setProperty(&amp;p);
  
      delete d;
  }
  </code></pre>