I l@ve RuBoard Previous Section Next Section

4.8 Implementing a Copy Assignment Operator

By default, when we assign one class object with another, as in



Triangular tri1( 8 ), tri2( 8, 9 ); 


tri1 = tri2; 

the data members of the class are copied in turn. In our example, _length, _beg_pos, and _next are copied from tri2 to tri1. This is called default memberwise copy.

In the case of the Triangular class, the default memberwise copy semantics are sufficient; there is nothing we need to do explicitly. In the case of the Section 4.2 Matrix class, however, the default memberwise behavior is not adequate. The reasons for this are discussed in the Default Memberwise Initialization subsection of Section 4.2.

The Matrix class requires both a copy constructor and a copy assignment operator. Here is how we might define the Matrix copy assignment operator:



Matrix& Matrix:: 


operator=( const Matrix &rhs ) 


{ 


   if ( this != &rhs ) 


   { 


        _row = rhs._row; _col = rhs._col; 


        int elem_cnt = _row * _col; 





        delete [] _pmat; 


        _pmat = new double[ elem_cnt ]; 


        for ( int ix = 0; ix < elem_cnt; ++ix ] 


              _pmat[ ix ] = rhs._pmat[ ix ]; 


   } 





   return *this; 


}; 

If the class designer provides an explicit instance of the copy assignment operator, that instance is used in place of default memberwise initialization. The source code of the user need not change, although it must be recompiled.

(Strictly speaking, this implementation is not exception-safe. See [SUTTER99] for a discussion.)

    I l@ve RuBoard Previous Section Next Section