Say I want to override the operator =
so I can do something like
Poly p1; // an object representing a polynomial
Poly p2; // another object of the
p2 = p1
is a shorthand for p2.operator=(p1)
. It is just calling your operator=
function, which is returning a reference to p2
, which you are then ignoring. To make this clear, let's call it assign
instead of operator=
:
Poly& Poly::assign(const Poly &source) {
.
.
.
return *this;
}
Now instead of p2 = p1
, you would write
p2.assign(p1);
In this case, the result of calling assign
is being ignored, but you don't have to ignore it. For example, you could write:
p3.assign(p2.assign(p1));
Using operator=
instead of assign
, this becomes
p3 = (p2 = p1);
but since assignment is right-associative, this can also be written as
p3 = p2 = p1;
This form of being able to do multiple assignments at once originally comes from C and has been preserved in C++ through the convention of returning *this
in operator=()
.