For example,
Number operator+(Number a, Number b) {
return Number(a.x + b.x);
}
Would this cause some kind of “unable to access private member error”. I understand that if I don’t pass by reference, the Number a, and Number b are copied on the stack and used in the body of the function. However, I don’t see why they do not allow access to the originals’ private members. How am I misunderstanding the concept of an object? Also how come friend and member function don’t need to pass by reference?
operator+is an unbound function, i.e. it is not a member ofNumberso, this is the rule, it has no implicit access to private members.The rule is not affected by you passing
Numberobjects by value or by reference. Access protection is applied to every access to aNumberobject, even if it is your private, stack-based copy.There are at least three ways out:
Number operator+(Number, Number)a friend ofNumberxso the variable is accessible.+=operator as a member of the class and implement the free operator in terms of it:return Number(a) += b;