title: Recursive Destructors in C++
body: <p>Suppose I have a class similar to the following:</p>
  
  <pre><code>#include &lt;vector&gt;
  
  class element
  {
  public:
     element();
     ~element();
  
     virtual void my_func();
  
  private:
     std::vector&lt;element*&gt; _elements;
  };
  </code></pre>
  
  <p>How would I go about implementing the destructor?  </p>
  
  <p>I was thinking something like this, but I'm not sure. I am worried about memory leaks since I'm relatively new to C++.</p>
  
  <pre><code>void element::destroy()
  {
     for(int i = 0; i &lt; _elements.size(); ++i)
        _elements.at(i)-&gt;destroy();
  
     if(this != NULL) 
        delete this;
  }
  
  element::~element()
  {
      destroy();
  }
  </code></pre>
  
  <p>Thank you.</p>
  
  <p>PS:
  Here is a sample main:</p>
  
  <pre><code>int main()
  {
     element* el_1 = new element();
     element* el_2 = new element();
     element* el_3 = new element();
  
     el_1.add_element(el_2);
     el_2.add_element(el_3);
  
     return 0;
  }
  </code></pre>
  
  <p>Also, what if I do this (aka don't use <code>new</code>):</p>
  
  <pre><code>int main()
  {
     element el_1;
     element el_2;
     element el_3;
  
     el_1.add_element(&amp;el_2);
     el_2.add_element(&amp;el_3);
  
     return 0;
  }
  </code></pre>