blastoise
blastoise

Reputation: 119

What's the difference between string.function() or function(string) in C++?

In some cases in c++ we use entities as string.length() but sometimes we use them as reverse(string.begin, string.end). What's the difference between the two? How can I determine when to use which form?

Upvotes: 0

Views: 1054

Answers (2)

Richard
Richard

Reputation: 8758

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.

Upvotes: 0

gchen
gchen

Reputation: 1173

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(it's a class defined in <string>). Primitive types(int, double, char...) don't have any methods.

Upvotes: 5

Related Questions