B. Kostas
B. Kostas

Reputation: 683

Why do i need both std and string library to use strings in c++

I know that string type exists in namespace std. I also know there is the <string> library which needs to be included in order to use the string type. My question is: why do i need both (to include the library and use the std namespace) to define a string? Why cant i just use it by including the library? More generally, what does the namespace std contains that is missing from the library?

Upvotes: 5

Views: 2477

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153830

Namespaces and headers are two separate concepts doing entirely different things:

  1. The header <string> declares the various entities related to the strings library like the class template std::basic_string, some typedefs like std::string and std::wstring, and some functions.
  2. Namespaces are used to group related functionality and allow use of the same names in different namespaces. For example, a "vector" is essentially an array for some (this is the view taken by the standard C++ library defining this name in namespace std) while in other contexts it is a mathematical entity.

When you included <string> you got all entities related to the strings library declared inside namespace std. Some people object to the idea to use std::string because it is so much easier to use string instead. To aide this practice a using directive, i.e., a statement like using namespace std; can be used to look in namespace std for entities when looking up names. That is, the using directive merely makes names available without qualification.

Upvotes: 3

Christian Hackl
Christian Hackl

Reputation: 27528

Look at it this way: std::string is the complete name of the type, much like "M. Kostas" is your complete name.

#include <string> gives you std::string. You can call it string only if you have first established the correct context, e.g. by using namespace std or by using std::string, or if you yourself happen to be library code within namespace std { /* ... */ }.

Again, consider the analogy with family names. I can only refer to you by "M." if I have first established that I am talking about the "Kostas" family (= using namespace std), or if I previously said that by "M." I actually mean "M. Kostas" (= using std::string) , or if I am myself a member of the "Kostas" family (= namespace std { /* ... */ }).

Note that you should (in the opinion of many programmers, at least, mine included) rarely use using namespace std or using std::string. It's often better to just use complete names everywhere. At global scope in header files, using shortcuts is even no longer a matter of style but can lead to real technical problems.

Upvotes: 2

Related Questions