Copy Constructors and Assignment Operators

   

Reading: Dietel Chapter 8

   

Dynamically Allocated Memory Problems

Copy constructor for our Array class:

   Array :: Array ( const Array& A )
    {
        array_size = A.array_size;        // can copy this member directly

        data_elements = new int [ array_size ];       // must allocate new memory

        for ( int i=0; i < array_size; i++ )               // want same contents in new memory
            data_elements [ i ] = A.data_elements [ i ];
    }

Syntax notes

Preventing Leaks of Dynamically-Allocated Memory

    Assignment operator for Array class:

Array& Array :: operator = (const Array& rhs)
{
if ( this != &rhs )  // so we don't clobber during self-assignment

    {
    delete [ ] data_elements;   // free memory previously allocated to lhs

    array_size = rhs.array_size;   // copy rhs size into lhs
    data_elements = new int [ array_size ]; // allocate new size array
    for (int i = 0; j < array_size; i++ )   // copy array contents of rhs
        data_elements[ i ] = rhs.data_elements [ i ];
    }

return *this;

}

Syntax notes:

  • We want to emulate behavior of built-in = operator on statements like:
        int x, y, z;
  • y = x = z;
        We want to assign z to x, and then assign that value to y.
        Precedence and associativity already defined; we need only return a
         (reference to) the value assigned.
  • x = x;
        This is allowed by the language; we want to make sure we don't 
           modify the rhs. 
        Perform the check this != &rhs before modifying this
  • ( x = y ) = z; 
        Generally useless, but can be done. 
        Assignment must return a (non-const) reference to the (lhs) Array.