OOPortal OOPortal


Operator Overloading  «Prev

Overloading the assignment operator

and

Program Dissection

vect& vect::operator=(const vect& v)
{
   assert(v.size == size);
   for (int i = 0; i < size; ++i)
      p[i] = v.p[i];
   return (*this);
}

vect& vect::operator=(const vect& v)

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.

assert(v.size == size);

This guarantees that the sizes are compatible.
for (int i = 0; i < size; ++i)
   p[i] = v.p[i];
return (*this);

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.