OOPortal OOPortal


Operator Overloading  «Prev  Next»
Lesson 10Overloading the assignment operator
ObjectiveMember function that overloads the assignment operator

Overloading Assignment Operator =

Write a member function that overloads the assignment operator for the matrix class so that the operator assigns one two-dimensional array to another.
Before looking at overloading the assignment operator, you may want to review the use of reference declaration.
Look at the binary operator overloading by focusing on the safe array class from the Building Classes in C++ course.
It would be convenient to assign one array to another. We can specify the behavior of assignment by overloading the assignment operator (=). It is good style to maintain consistency with standard usage and avoid creating personal algebras.

New Assignment
We can add the following member function, which overloads the assignment operator for the vect class:

Program dissection

Move your mouse cursor over the 1) operator= 2) assert and 3) for loop to to read a description of their purpose.

  1. The "operator=()" function returns reference to "vect" and has one explicit argument of type reference to "vect". The first argument of the assignment operator is the implicit argument. The function could have been written to return void, but then it would not have allowed multiple assignment.
  2. This guarantees that the sizes are compatible.
  3. The explicit argument "v.p[]" will be the right side of the assignment. The implicit argument "p[]" will be the left side of the assignment. The self-referential pointer is dereferenced and passed back as the value of the expression. This allows multiple assignment with right-to-left associativity to be defined.
operator=()
Operator Program Dissection

Now with the class vect, the following expressions are meaningful:
a = b;                  //a, b are type vect
a = b= c;             //a, b, c are type vect
a = vect(data, DSIZE);  //convert array data[DSIZE]

Overloading Assignment Exercise

Click the Exercise link below to write a member function that overloads the assignment operator for the matrix class so that the operator assigns one two-dimensional array to another.
Overloading Assignment Exercise