I read that an overloaded operator declared as member function is asymmetric because it can have only one parameter and the other parameter passed automatically is the this pointer. So no standard exists to compare them. On the other hand, overloaded operator declared as a friend is symmetric because we pass two arguments of the same type and hence, they can be compared.
My question is that when i can still compare a pointer’s lvalue to a reference, why are friends preferred? (using an asymmetric version gives the same results as symmetric)
Why do STL algorithms use only symmetric versions?
If you define your operator overloaded function as member function, then the compiler translates expressions like
s1 + s2intos1.operator+(s2). That means, the operator overloaded member function gets invoked on the first operand. That is how member functions work!But what if the first operand is not a class? There’s a major problem if we want to overload an operator where the first operand is not a class type, rather say
double. So you cannot write like this10.0 + s2. However, you can write operator overloaded member function for expressions likes1 + 10.0.To solve this ordering problem, we define operator overloaded function as
friendIF it needs to accessprivatemembers. Make itfriendONLY when it needs to access private members. Otherwise simply make it non-friend non-member function to improve encapsulation!Read these :
A slight problem of ordering in operands
How Non-Member Functions Improve Encapsulation