title: Class members and explicit stack/heap allocation
body: <p>Let's say we have 4 classes as follows:</p>
  
  <pre><code>class A
  {
      public:           
          A(void) : m_B()
          {
          }
      private:
          B m_B;
  }
  
  class B
  {
      public:            
          B(void)
          {
             m_i = 1;
          }
      private:
          int m_i;
  }
  
  class C
  {
      public:           
          C(void) 
          {
              m_D = new D();
          }
          ~C(void) 
          {
              delete m_D;
          }
      private:
          D *m_D;
  }
  
  class D
  {
      public:           
          D(void)
          {
             m_i = 1;
          }
      private:
          int m_i;
  }
  </code></pre>
  
  <p>Lets say there are 4 cases:</p>
  
  <p>case 1: A externally allocated on the stack, B internally allocated on the stack</p>
  
  <pre><code>A myA1;
  </code></pre>
  
  <p>case 2: A externally allocated on the heap, B internally allocated on the stack</p>
  
  <pre><code>A *myA2 = new A();
  </code></pre>
  
  <p>case 3: C externally allocated on the stack, D internally allocated on the heap</p>
  
  <pre><code>C myC1;
  </code></pre>
  
  <p>case 4: C externally allocated on the heap, D internally allocated on the heap</p>
  
  <pre><code>C *myC2 = new C();
  </code></pre>
  
  <p>What goes on in each of these cases? For example, in case 2, I understand the pointer myA2 is allocated on the stack, the A object exists in the heap, but what about the m_B attribute? I assume space on the heap allocated for it as well because it wouldn't make sense for an object to exist in heap space and then it's attribute goes out of scope. If this is true then does that mean the external heap allocation overrides the internal stack allocation? </p>
  
  <p>What about case 3, myC1 is allocated on the stack, however m_D is allocated on the heap. What happens here? Are the two parts split across memory? If I removed the 'delete m_D' from the destructor and myC1 went out of scope, would there be a memory leak for the space allocated on the heap for m_D?</p>
  
  <p>If there are any tutorials/articles that go over this in detail I would love a link. </p>