title: What happens to class members when malloc is used instead of new?
body: <p>I'm studying for a final exam and I stumbled upon a curious question that was part of the exam our teacher gave last year to some poor souls. The question goes something like this:</p>
  
  <blockquote>
    <p>Is the following program correct, or not? If it is, write down what the program outputs. If it's not, write down why.</p>
  </blockquote>
  
  <p>The program:</p>
  
  <pre><code>#include&lt;iostream.h&gt;
  class cls
  {     int x;
        public: cls() { x=23; }
        int get_x(){ return x; } };
  int main()
  {     cls *p1, *p2;
        p1=new cls;
        p2=(cls*)malloc(sizeof(cls));
        int x=p1-&gt;get_x()+p2-&gt;get_x();
        cout&lt;&lt;x;
        return 0;
  }
  </code></pre>
  
  <p>My first instinct was to answer with "the program is not correct, as <code>new</code> should be used instead of <code>malloc</code>". However, after compiling the program and seeing it output <code>23</code> I realize that that answer might not be correct.</p>
  
  <p>The problem is that I was expecting <code>p2-&gt;get_x()</code> to return some arbitrary number (whatever happened to be in that spot of the memory when <code>malloc</code> was called). However, it returned 0. I'm not sure whether this is a coincidence or if class members are initialized with 0 when it is <code>malloc</code>-ed.</p>
  
  <ul>
  <li>Is this behavior (<code>p2-&gt;x</code> being 0 after <code>malloc</code>) the default? Should I have <strong>expected</strong> this?</li>
  <li>What would <strong>your</strong> answer to my teacher's question be? (besides forgetting to <code>#include &lt;stdlib.h&gt;</code> for <code>malloc</code> :P)</li>
  </ul>