explanation

Hi,
could someone explain to me the meaning of the line of code shown below?

the book is about self-assignment .... ( book: Bruce Eckel vol. 1)

1
2
3
4
5
6
7
8
  Integer& operator+=(Integer& left, const Integer& right) 
{ 
  if(&left == &right) {/* self-assignment */}  // QUESTION

  left.i += right.i;
 
   return  left;
 }
Last edited on

Integer& operator+=(Integer& left, const Integer& right)

This appears to be a function signature that returns a copy(dereferenced) of a class called Integer; This method is overloading the += operator - Then as an input perimeters where the left input is mutable e.g it can change value and the right hand side is constant and will not change.

1
2
{ 
  if(&left == &right) {/* self-assignment */}  // QUESTION 


This code says if the value of the left and side is equal to the right hand side then call the default self assignment operator. https://en.wikipedia.org/wiki/Assignment_operator_%28C%2B%2B%29


Then if the above is true or not (in ether case )
run the below code;

left.i += right.i;

this is logically equivalent to
left.i = left.i + righti;



1
2
3
 
   return  left;
 }


then return the copy(value) of the left object.
thx Bdanielz.
perfect explanation
Topic archived. No new replies allowed.