title: throwing exception from constructor in C++
body: <p>I have read several articles here and else where that it is OK to throw exception from constructor. However, I have noticed that it doesn't call destructor of base class or its data members if an exception is thrown from the constructor. Consider the following example:</p>
  
  <pre><code>#include &lt;iostream&gt;
  using namespace std;
  struct C
  {
      C() { cout &lt;&lt; __FUNCTION__ &lt;&lt; endl;  }
      ~C() { cout &lt;&lt; __FUNCTION__ &lt;&lt; endl; }
  };
  
  struct E: public C
  {
      C c;
      E() { cout &lt;&lt; __FUNCTION__ &lt;&lt; endl; throw 4; }
      ~E() { cout &lt;&lt; __FUNCTION__ &lt;&lt; endl; }
  };
  
  int main()
  {
      E e;
  }
  
  
  $ g++ test.cpp; ./a.exe
  C
  C
  E
  terminate called after throwing an instance of 'int'
  Aborted (core dumped)
  </code></pre>
  
  <p>In this case, E's constructor throws an exception but C's destructor as a data member or as a base class is not called. Now if C's destructor performs some cleanup operation like closing files/sockets and deleting heap allocations, this can cause problems. </p>
  
  <p>So my question is why and when is it OK to throw exceptions from constructors. </p>