flumpb
flumpb

Reputation: 1776

When should I use non-member operator overloading?

Should I be using non-member overload or member overload? How do I tell which I should use?

Upvotes: 0

Views: 88

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477454

If you're thinking about something like operator< or swap, there's a rule of thumb ( though it's not terribly strict or mandatory):

If the function only requires access to the public interface of your class, make it a free non-member function. Otherwise make it a member function. (Alternatively you may consider a friend free function.)

Note that for overloads of operators you will need at least one of the operands to be a user-defined type.

The design advantage of a free function is that you can make it a template and get M + N complexity rather than M * N if you were to implement a version of the operator for each class for which it's applicable. This may or may not be relevant to your situation.

See also Nawaz's very fine answer on the subject.

Upvotes: 3

Related Questions