3

In order to use strings I need to include the string header, so that its implementation becomes available. But if that is so, why do I still need to add the line using std::string?

Why doesn't it already know about the string data type?

#include <string>

using std::string;

int main() {
    string s1;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vanmarcke
  • 133
  • 1
  • 1
  • 7

4 Answers4

8

Because string is defined within namespace called std.

you can write std::string everywhere where <string> is included but you can add using std::string and don't use namespace in the scope (so std::string might be reffered to as string). You can place it for example inside the function and then it applies only to that function:

#include <string>

void foo() {
    using std::string;

    string a; //OK
}

void bar() {
    std::string b; //OK
    string c; //ERROR: identifier "string" is undefined
}
Graham
  • 7,431
  • 18
  • 59
  • 84
mpiatek
  • 1,313
  • 15
  • 16
8

using std::string; doesn't mean you can now use this type, but you can use this type without having to specify the namespace std:: before the name of the type.

The following code is correct:

#include <string>

int main()
{
    std::string s1;
    return 0;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Caduchon
  • 4,574
  • 4
  • 26
  • 67
2

Because the declaration of class string is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did.

dmi
  • 1,424
  • 1
  • 9
  • 9
1

Namespace is an additional feature of C++, which is defining the scope of a variable, function or object and avoiding the name collision. Here, the string object is defined in the std namespace.

std is the standard namespace. cout, cin, string and a lot of other things are defined in it.

The header <string> declares the various entities related to the strings library, whereas namespaces are used to group related functionality and allow use of the same names in different namespaces.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
msc
  • 33,420
  • 29
  • 119
  • 214