Whats the difference between string.function() or function(string) in C++?
Whats the difference between string.function() or function(string) in C++?
If we define:
std::string string;
string.length(); // is calling the length method/member function of the string object.
which is http://en.cppreference.com/w/cpp/string/basic_string/size
On the other hand,
reverse(string.begin(), string.end());
is calling a free function(not a method/member function) defined in the STL algorithm library(http://en.cppreference.com/w/cpp/algorithm/reverse), thus we cannot do string.reverse(...)
A method should be called on an object. A free function should be called without an object.
By the way, string
is not a primitive type(its a class defined in <string>
). Primitive types(int
, double
, char
…) dont have any methods.
How can I determine when to use which form?
Whatever fits your needs best. Technically there is no downside either using e.g. std::string::find
or std::find
. While member functions like std::string::find
might offer easier usage for their container type, they are limited to only this very container type (e.g. std::string
):
The motivation of the algorithm library (e.g. where std::reverse
belongs to) is to give the user one interface which works with different containers like std::string
, std::vector
, std::map
etc. This is achieved by using iterators which every container has.