Possible Duplicate:
Operator overloading
What is the differences between the following ways to overload operator== ?
// stroustrup way
friend bool operator== (MyClass &lhs, MyClass &rhs);
and
// as taught in other places, including caltech
bool MyClass::operator== (MyClass &rhs);
Which way is better?
Arguments should be
const
:This is preferred as it works when the first argument can be implicitly constructed. For example, if
std::string
only had a member functionoperator==
, then"abc" == my_std_string
would not invoke it! But, the non-member function can be invoked by implicitly constructing a string from "abc" (better yet in this particular case, a separatebool operator==(const char*, const std::string&)
can be provided for performance reasons, but the point still stands - non-member functions can help ensure the operator works with the user-defined-type on either side).Separately, implicit constructors are a bit dangerous - and you want to think hard about the convenience versus danger of using them.
A final point: you only need to make the non-member
operator==
afriend
if there's no other way to access the data you need to compare. Otherwise, you can declare/define it outside the class, optionally inline if you want the implementation in a header that may be included from multiple translation units eventually linked into the same executable. Not much harm though, and making it a friend is the only way to put the definition inside a class template, where you don't have to repeat the "template " stuff and parameters....First is external friend function (free function)
Second is member function
You should use second variant always then you can
You should use first variant in case: 1) First argument is the external (library) class
2) Operator's logic not related to your class and must be implemented separately
(because your class can't know all about classes that may need in compare operator)
This :
is a function, which compares two objects.
This :
is a member function.
You should use the one proposed by your coding standard, or use the one you prefer. None is better. Some people (including myself) prefer to have the comparison operator as a function, other prefer it as a member function.
By the way, the parameters should be of
const MyClass &
type.