Reputation: 683
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
Reputation: 153830
Namespaces and headers are two separate concepts doing entirely different things:
<string>
declares the various entities related to the strings library like the class template std::basic_string
, some typedef
s like std::string
and std::wstring
, and some functions.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
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