title: C++ Copy Constructor and Assignment Operator Define
body: <p>C++ Copy Constructor and Assignment Operator Define</p>
  
  <p>Could anybody help me correct the following copy constructor and assignment operator?</p>
  
  <ol>
  <li><p>as you see, assignment operator seems to work well; I ran it and it works.
  Do I define the assignment operator correct? Please let me know.</p></li>
  <li><p>This crashes with the copy constructor...
  How can I fix the copy constructor?</p></li>
  </ol>
  
  <p>Please help me.</p>
  
  <pre><code> #include &lt;iostream&gt;
   using namespace std;
  
   class IntP
   {
   private:
      unsigned int* counts;
      unsigned int numP;
      unsigned int size;
  
   public:
      IntP(); // Default Constructor
      IntP(int n); // Constructor
      IntP(const IntP&amp; a); // Copy Constructor
      IntP&amp; operator= (const IntP&amp; a); // Assignment Operator
      ~IntP(); // Destructor
      void printIntP() const;
   };
  
   IntP::IntP() // Default Constructor
   {
     counts = new unsigned int[101] (); // initialize array of size 101 to all 0s
     numP = 0;
     size = 101;
   }
  
   IntP::IntP(int n) // Constructor
   {
     counts = new unsigned int[n+1] (); // initialize array of size n+1 to all 0s
     counts[n] = 1;
     numP = 1;
     size = n+1;
   }
  
   // ????????????
   // 
   IntP::IntP(const IntP&amp; a) // Copy Constructor
   {
     this-&gt;size = a.size;
     this-&gt;numP = a.numP;
     for (int i=0; i &lt; (int) this-&gt;size; i++)
        this-&gt;counts[i] = a.counts[i]; 
   }
  
   // ??????????? 
   // Correct Implementation?
   // without delete operator, we have memory leak? but it compiles without error??? 
   IntP&amp; IntP::operator= (const IntP&amp; a) // Assignment Operator
   {
     if (this != &amp;a)
     {
       delete [] counts; // Get rid of old counts
       size = a.size; 
       numP = a.numP;
       counts = new unsigned int[size+1];
       counts[size] = 1;
       for (int i=0; i &lt; (int) this-&gt;size; i++)
          counts[i] = a.counts[i]; 
     }
     return *this;
   }
  
   IntP::~IntP() { delete [] counts; }
  
   void IntP::printIntP() const
   {
      cout &lt;&lt; "The size of array is " &lt;&lt; this-&gt;size &lt;&lt; endl;
      cout &lt;&lt; "The numP variable becomes " &lt;&lt; this-&gt;numP &lt;&lt; endl;
  
      int i = 0;
      while ( i != (int) this-&gt;size )
      {
        cout &lt;&lt; counts[i];
        if ( i != (int) this-&gt;size-1 ) cout &lt;&lt; " , ";
        i++;
      } 
  
      cout &lt;&lt; endl &lt;&lt; endl;
   }
  
   int main (void)
   {
  
   IntP ip2(200); 
   IntP ip3; 
   ip3 = ip2;
  
  
  
   IntP ip1(100); 
  
   cout &lt;&lt; "Print out   ip1 object  after IntP ip1(100); " &lt;&lt; endl; 
   ip1.printIntP(); 
  
  
   IntP ip4(ip1); 
  
   cout &lt;&lt; "Print out   ip4 object  after IntP ip4(ip1); " &lt;&lt; endl; 
   ip4.printIntP();
  
   system("pause"); return 0;
   }
  </code></pre>