Why are those C++11 new functions of header <string>
(stod
, stof
, stoull
) not member functions of the string
class ?
Isn't more C++ compliant to write mystring.stod(...)
rather than stod(mystring,...)
?
It is a surprise to many, but C++ is not an Object-Oriented language (unlike Java or C#).
C++ is a multi-paradigm language, and therefore tries to use the best tool for the job whenever possible. In this instance, a free-function is the right tool.
Guideline: Prefer non-member non-friend functions to member functions (from Efficient C++, Item 23)
Reason: a member function or friend function has access to the class internals whereas a non-member non-friend function does not; therefore using a non-member non-friend function increases encapsulation.
Exception: when a member function or friend function provides a significant advantage (such as performance), then it is worth considering despite the extra coupling. For example even though std::find
works really well, associative containers such as std::set
provide a member-function std::set::find
which works in O(log N) instead of O(N).