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?
For binary operators, one limitation of member functions is that the left object must be of your class type. This can limit using the operator symmetrically.
Consider a simple string class:
class str
{
public:
str(const char *);
str(const str &other);
};
If you implement operator+ as a member function, while str("1") + "2"
will compile, "1" + str("2")
will not compile.
But if you implement operator+ as a non-member function, then both of those statements will be legal.
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