title: How is a object with local variables stored in the heap?
body: <p>Suppose I have a class that has local variables, like this one:</p>
  
  <pre><code>class Object{
   private:
   int number1, number2, number3;
  
  
   public:
   Object(){
   number1=0;
   number2=0;
   number3=0;
   }
  
  }
  </code></pre>
  
  <p>Now let's suppose I use it in my main program:</p>
  
  <pre><code>int main (){
  Object obj1();
  }
  </code></pre>
  
  <p>I created my object locally in main. Since I did not use "new" it does not use the heap. All the object's variables (and the object itself) are stored in the stack.</p>
  
  <p>Now suppose I used new in main, like this:</p>
  
  <pre><code>int main (){
  Object p= new obj1();
  }
  </code></pre>
  
  <p>Now I only have one variable in my main: a pointer that points to obj1 in the heap. </p>
  
  <p>My class notes say this is possible and correct: that you can dynamically create an object that has local variables. But how exactly is the compiler able to create the object in the heap? My object's variables number1, number2 and number3 do not use new. They are local variables and local variables need a local scope. I get that the object "p" is on the heap because we used "new". But what about its members? They don't use new. Is there some kind of automatic cast so that these local variables are made dynamic?</p>