I am currently creating a utility class that will have overloaded operators in it. What are the pros and cons of either making them member or non-member (friend
) functions? Or does it matter at all? Maybe there is a best practice for this?
I am currently creating a utility class that will have overloaded operators in it. What are the pros and cons of either making them member or non-member (friend
) functions? Or does it matter at all? Maybe there is a best practice for this?
I'd go with "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices": if you can do it as non-member function, do it as non-member function (in the same namespace).
One of the reasons: it works better with implicit type conversion. An Example: You have a complex class with an overloaded operator*. If you want to write 2.0 * aComplexNumber, you need the operator* to be a non-member function.
Another reason: less coupling. Non-member-functions a less closely coupled than member functions. This is almost always a good thing.