title: i need to know how compiler work with destructors in cpp
body: <p>Lets say I have 2 diffrent classes.</p>
  
  <p>Why when I put class <code>A</code> object as data member inside class <code>B</code>, the class that getting destroyed first is class <code>B</code> and then class A but when i put class <code>A</code> object in the builder of class <code>B</code> then class <code>A</code> getting destroyed first and then class <code>B</code>? for example:</p>
  
  <pre><code>class A {
  public:
      ~A() { std::cout &lt;&lt; "Deleting A\n"; }
  };
  
  class B {
  private:
      A object;
  public:
      ~B() { std::cout &lt;&lt; "Deleting B\n"; }
  };
  
  int main( void ) {
      B test;
      return 0;
  }
  </code></pre>
  
  <p>result:</p>
  
  <blockquote>
    <p>Deleting B<br>
    Deleting A</p>
  </blockquote>
  
  <p>But the next example gives me the opposite result :</p>
  
  <pre><code>class A {
  public:
      ~A() { std::cout &lt;&lt; "Deleting A\n"; }
  };
  
  class B {
  public:
      B() { A object; }
      ~B() { std::cout &lt;&lt; "Deleting B\n"; }
  };
  
  int main( void ) {
      B test;
      return 0;
  }
  </code></pre>
  
  <p>result:</p>
  
  <blockquote>
    <p>Deleting A<br>
    Deleting B</p>
  </blockquote>