title: How do I do a deep copy in c++
body: <p>I am trying to do a deep copy of class <code>B</code>, but A doesn't get set.</p>
  
  <p>Why does <code>b3-&gt;print</code> return a garbage number instead of <code>1</code>?</p>
  
  <p>From what I understand, b2 and b3 are both pointing to the same A object. but I created a new object on the heap with B's copy constructor. so why are they both still poiting to the same object?</p>
  
  <p>I hope this makes sense.</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  class A{
        int num;
  public:
         A(int n):num(n){ cout&lt;&lt; "A "&lt;&lt; num &lt;&lt; " constructor" &lt;&lt;endl;}  
         ~A(){ cout&lt;&lt; "A "&lt;&lt; num &lt;&lt;" destructor. " &lt;&lt;endl; }   
  
         int print(){
          cout&lt;&lt; num&lt;&lt; endl;
         }
  };
  
  class B{
        A *a;
        int num;
  public:
         B(int n):num(n){
             a = new A(n);
             cout&lt;&lt; "B "&lt;&lt; num &lt;&lt;" constructor" &lt;&lt;endl;    
         }  
         ~B(){
              delete a; 
              cout&lt;&lt; "B "&lt;&lt; num &lt;&lt;" destructor"&lt;&lt;endl; 
         }    
         // Copy contructor
         B(const B &amp; b): a(new A(b.num)){ 
         } 
  
         &lt;strike&gt;int&lt;\strike&gt; void print(){
          cout&lt;&lt; num &lt;&lt; endl;
         }
  
         int get_num(){
             return num;
         }
  };
  
  int main(int argc, char *argv[])
  { 
      B *b2 = new B(1);
      B *b3(b2);
      b2-&gt;print();
      delete b2;
      b3-&gt;print();
      system("PAUSE");
      return EXIT_SUCCESS;
  }
  </code></pre>