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?
// stroustrup way
friend bool operator== (MyClass &lhs, MyClass &rhs);
Arguments should be const
:
friend bool operator==(const MyClass& lhs, const MyClass& rhs);
This is preferred as it works when the first argument can be implicitly constructed. For example, if std::string
only had a member function operator==
, 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 separate bool 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.
Similarly, if you had ObjectOfAnotherClassType == ObjectOfMyClassType
, and AnotherClass
sported a casting operator such as operator MyClass() const
, then the non-member/friend operator==
would allow the cast to kick in and be able to do the comparison; the member operator==
form would not.
A final point: you only need to make the non-member operator==
a friend
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 <typename ...>
" stuff and parameters....
First is external friend function (free function)
friend bool operator== (MyClass &lhs, MyClass &rhs);
Second is member function
bool MyClass::operator== (MyClass &rhs);
You should use second variant always then you can
You should use first variant in case: 1) First argument is the external (library) class
friend ostream& operator<< (ostream &out, MyClass &m)
2) Operator's logic not related to your class and must be implemented separately
friend bool operator(const MyClass& my, const std::string& string_form)
(because your class can't know all about classes that may need in compare operator)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With