The existing answers are great and certainly for the standards committee were vital for this purpose. But there is another issue that I think is important enough to mention.
With free functions, you have the ability to modify an interface without changing the definition of a class. You can make any type "gettable" simply by specializing the global get
. With a member function, you would have to directly modify the class.
Range-based for
looks for member begin/end
on class types, but it also looks for non-member begin/end
via ADL. These APIs can be used with any container, even those that don't have begin/end
functions. You can specialize it for, for example, LibXML2 element types, such that you can range-based for
over xmlElement*
's.
You can't do that if they had to be member functions.
In C++, free functions are a natural interface for many operations that could be done on many different kinds of classes.