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;
}
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.using std::string;
doesn't mean you can now use this type, but you can use this type without having to specify the namespacestd::
before the name of the type.The following code is correct:
Because
string
is defined within namespace calledstd
.you can write
std::string
everywhere where<string>
is included but you can addusing std::string
and don't use namespace in the scope (sostd::string
might be reffered to asstring
). You can place it for example inside the function and then it applies only to that function:Namespace
is an additional feature of C++, which is defining the scope of a variable, function or object and avoiding the name collision. Here, thestring
object is defined in thestd
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.