Why We Can't Be Friends

Overloads of operators should NOT be done with friends. Friends violate privacy principles.

The book uses friends only because the non-friend version is harder to understand.* However, no professional programmer uses friends except perhaps to overload << or >> which can only be done with a friend. The proper way to implement the prototype is not:

friend const Money operator +(const Money& amount1, const Money& amount2);

but rather is:

const Money operator +(const Money& rhs);

In the implementation we rely on the fact that every nonstatic member function has a pointer to the instance of the calling variable and it is called this. So we can write:

const Money operator +(const Money& rhs){
   this->cents += rhs.cents;
   dollars += rhs.dollars;// note that this-> is implied an usually left off


Note that in an operation such as A + B or A = B the this pointer represents A.


Addendum: After an email exchange with Walter Savitch I found that I misunderstood his motivation. I now understand his reasoning. He maintains that since m1 + 24 is allowed, 24 + m1 should be allowed. Without friends, the former is and the latter is not.

If the second form is necessary you would have no choice but to use a friend two argument form (as in the case of overloading << where you have no choice but to use a friend because you must return an ostream type).