c2=c1: A simple “=“ operation?
First, keep in mind that you are calling a member function of the cube “c2” with “c1” as the argument.
// the assignment operator
cube& cube::operator= (const cube& c)
if ( this == &c) return (*this) ;
So “length” refers to c1.length, the length of cube c1
c.length refers to the length value of cube c2.
Here we assign the length value of c2 to c1, as it should be.
We return a reference to c1 (the this pointer points to the object whose member function this is).
But before we check if the objects happen to be the same, that is, we write something like c1 = c1;
Why are we returning a reference to “us” (the this pointer)? After we assign the length, we are done, aren’t we?
Yes. But we must support constructs like
which means “assign c1 to c2. Then assign c2 to c3”, or
- we invoke a member function of c2 with the parameter “reference to c1”.
- we assign c1’s length to c2’s length, and return a reference to c2.
- then we invoke a member function of c3 with what’s right of the assignment (=), that is, the reference to c2 returned from the function.
- we assign the length value of c2 (through the reference) to c3’s length.
Note: We haven’t taken care of the Color yet! Wait.