TITLE: global operators versus member operators (Newsgroups: comp.std.c++, 16 Feb 98) CAO: dq250@FreeNet.Carleton.CA (S. Cao) >Could someone tell me why when overloading the assignment (=) operator, >the operator overloading function has to be a member function? (which >is also required for (), [] and ->). I have checked several c++ books >I have, all of them only stated the rule but no further explanations. CLAMAGE: clamage@Eng.sun.com (Steve Clamage) The operators which do not need to be class members are those which have no predefined meaning for a class type. For example, if you write x+y where x or y has a class type, the code is invalid unless a declaration for an appropriate operator+ is in scope at the point of the call. Now suppose for class T you could write T& operator=(T&, const T&); // not a member of T Since assignment is predefined for all class types, the meaning of t1 = t2; // both of type T would depend on whether a declaration for the overloaded assignment were in scope. That's bad -- a source of very subtle bugs. You could argue that similar problems exist for all overloaded functions, but assignment is a fundamental, prefined operation. That's the main reason for requiring operator= to be a class member function. The main reason for requiring operator= to be in particular a *nonstatic* class member function applies to the other special operators as well. For a non-member operator function T1 operator@(T2, T3); // '@' is any operator type conversion is allowed on the left (first) operand. Often, that is exactly the effect we want. Overloading the addition operator that way allows us to write 1+x as well as x+1 without having to write two functions, assuming conversions from int to the type of x. Now consider assignment, [], and ->. If conversion occured on the left operand, you could create a temp object, operate on the temp, discard the temp, and the real operand would remain unaffected. It is very unlikely that you would want that behavior for these functions. Type conversion never occurs on the object ("this") parameter to a member function, so the problem does not arise. In the case where you really want to create a temp, you can do so explicitly via a cast. You won't introduce subtle bugs by the conversion happening invisibly.