What is the difference between operator overloading using the friend keyword and as a member function inside a class?
Also, what is the difference in the case of any unary operator overloading (i.e. as a friend vs. as a member function)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Jacob is correct… a
friendfunction declared within a class has access to that class, but it’s not inside the class at all, and everyone else has access to it.For an operator overload which is not a member of the class (also called a free function, it may be a friend, or maybe not), the arguments are the same as the operands. For one which is a member of a class, the first operand is the “implicit argument” which becomes
this.The implicit argument is different from the first argument to a free function in a few ways:
virtualoverload will be chosen by the dynamic type of the first operand, which is not possible with free functions without extra code.)The situation is the same for unary, binary, or n-ary (in the case of
operator()).Members privilege of mutation: Operators which change the first operand (eg
+=,=, prefix++) should be implemented as member functions, and should exclusively implement the guts of all overloads. Postfix++is a second-class citizen; it is implemented asObj ret = *this; ++ this; return ret;. Note that this sometimes extends to copy-constructors, which may contain*this = initializer.Rule of freedom for commuters: Only commutative operators (eg
/) should be free functions; all other operators (eg unary anything) should be members. Commutative operators inherently make a copy of the object; they are implemented asObj ret = lhs; ret @= rhs; return ret;where@is the commutative operator andlhsandrhsare left-hand side and right-hand side arguments, respectively.Golden rule of C++ friendship: Avoid friendship.
friendpollutes the semantics of a design. Overloading corollary: Overloading is simple if you follow the above rules, thenfriendis harmless.friending boilerplate overload definitions allows them to be placed inside theclass {braces.Note that some operators cannot be free functions:
=,->,[], and(), because the standard specifically says so in section 13.5. I think that’s all… I thought unary&and*were too, but I was apparently wrong. They should always be overloaded as members, though, and only after careful thought!