Search code examples
c++stringincludeusing

Why is using std::string still needed after #include <string>?


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;
}

Solution

  • 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
    }