title: c++ how to skip the call of parent's destructor
body: <p>The problem below is not very common, so I can't find anything online that could be of help:</p>
  
  <p>I have <code>class parent</code>, which <strong>must</strong> have the default constructor and destructor, I am not supposed to define anything about these two members. </p>
  
  <p>I need to take control of <code>ptr</code> destruction, it must be destructed only if it is not referenced, which is controlled by <code>counter</code> in <code>someclass</code>.</p>
  
  <pre><code>class parent {
  public:
     someclass * ptr;
  }
  class child: public parent {
  
     ~child() {                           //&lt;-- this line
        cout&lt;&lt;"in ~child!"&lt;&lt;endl;
        if(this-&gt;ptr == NULL)  cout&lt;&lt;"ptr is NULL"&lt;&lt;endl;
        this-&gt;ptr-&gt;delete_reference();    //&lt;-- here ptr = NULL
      }
  
      someclass* get_ptr() {
         return this-&gt;ptr;
      }
  }
  
  class someclass {
    void delete_reference() {
      counter--;
      if(counter == 0)   delete this;
  }
  </code></pre>
  
  <p>The problem is that in <code>this line</code> parent's default destructor is called and does <code>ptr = NULL</code>, as a result, <code>ptr</code> is not properly destructed. </p>
  
  <p>Is there a way to skip the call of ~parent with these restrictions? </p>
  
  <p>I also tried to remove inheritance, and have an instance of <code>parent</code> in <code>child</code>, but the same thing happens, parent's destructor is called again. </p>
  
  <p>Furthermore, I need <code>ptr</code> in <code>parent</code> because there are more child classes and they need to share this information.</p>
  
  <p>Thank you!</p>
  
  <p><strong>EDIT:</strong>
  OK as I understood, I got something wrong here... the problem is how ptr gets NULL. 
  As long as I confused the order of destructor calls, then the problem is not in <code>this line</code>.</p>
  
  <pre><code>void function() {
    child ch1;
    for(int i = 0; i&lt;1; i++) {
      cout&lt;&lt;iterating&lt;&lt;endl; 
      do_some_work(ch1);
    }
    if(ch1-&gt;get_ptr() != NULL) cout&lt;&lt;"ptr is OK"&lt;&lt;endl;
  
    return;
    //Here is the destructor ~child called (?)
  }
  
  int main() {
    function();
  
  }
  </code></pre>
  
  <p>The above calling is the way I use <code>child</code>. Inside <code>do_some_work</code> there is actually a lot of work that is difficult to describe here. </p>
  
  <p>The point is that after <code>do_some_work</code> finishes, <code>ptr</code> is OK. Then I suppose destructors are called and <code>ptr</code> seems to be <code>NULL</code>. </p>
  
  <p>So, the above will print:</p>
  
  <pre><code>iterating
  ptr is OK
  in child
  ptr is NULL
  Segmentation fault
  </code></pre>
  
  <p>Is there any explanation after this edit?</p>
  
  <p>Thank you all very much!</p>