C ++: when it makes sense to define functions outside the class

Possible duplicate:
When should functions be member functions?

Are there situations where it is better to define functions outside of classes or use static functions inside a class?

+3
source share
4 answers

There are some cases that should be non-member functions:

  • Operator overloads cannot 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 an implicit conversion to LHS and RHS for free overloads operators, but only for RHS to overload member operators.

  • std::swap using std::swap; swap(x,y);, "" ADL. swap , , , -. , ADL.

  • , - "C" . ++ ABI C , , , C.

, -, :

  • protected. - , .cpp, , . , .

, , - .

+4

(, Generic Programming), .

++ OO Generic. ;)

+2

. , , strcpy(), . .

+1

An important use of free functions is when the same function must have access to several objects. Everything that accesses only one object must be a member function, but if it changes several objects, it must be a free function.

0
source

All Articles