Possible Duplicate:
When should functions be member functions?
Are there situations when it is better to define functions outside of classes or should you use static functions inside a class?
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.
There are some cases that have to be non-member functions:
operator overloads can’t be static member functions (they can be non-static member functions), and in particular most binary operator overloads work better as non-member functions because you get implicit conversion on the LHS and RHS for free operator overloads but only on the RHS for member operator overloads.
std::swapis conventionally called asusing std::swap; swap(x,y);so that classes can “overload” it via ADL. Implementingswapconventionally therefore requires a non-member function, if only as a wrapper that calls a member function. The same would be true of other functions designed to be ADL-overloaded.Technically, static member functions can’t have “C” linkage and therefore aren’t suitable as callbacks when interfacing with other languages. In practice, C++ ABIs tend to make static functions call-compatible with C, provided of course that their parameters and return type exist in C.
So far I can think of one case that has to be a static member function rather than a free function:
protected. Private static member functions are normally pointless, because it’s normally better to define a free function with internal linkage in the .cpp file, where nobody else can even see it let alone call it. But I suppose occasionally you’d want one.Beyond that it’s really a style question, there isn’t very much practical difference between a static member function and a free function.