Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload operators as member function or non-member (friend) function?

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?

like image 315
Seth Avatar asked Dec 15 '09 06:12

Seth


1 Answers

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.

like image 155
R Samuel Klatchko Avatar answered Nov 09 '22 14:11

R Samuel Klatchko