开发者

C++: When is it appropriate to define functions outside of a class [duplicate]

This question already has answers here: Closed 11 years ago.

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开发者_StackOverflow社区 static functions inside a class?


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::swap is conventionally called as using std::swap; swap(x,y); so that classes can "overload" it via ADL. Implementing swap conventionally 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:

  • You want to use access specifier 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.


Free function are also a great way to write generic code properly (generic as in Generic Programming) as it helps extending interfaces without intrusively modify existing code.

C++ is both OO and Generic programming oriented. Pick yours ;)


Some functions need to be defined outside of a class. For example, functions like strcpy(), which don't act on class types. But they should be put into a namespace.


Important use of free functions is when the same function need to access more than one object. Anything that accesses only one object should be member function, but if it changes several objects, it should be a free function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜