Should I be using non-member overload or member overload? How do I tell which I should use?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you’re thinking about something like
operator<orswap, 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
friendfree 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 + Ncomplexity rather thanM * Nif 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.