Why we need #include <string>

Sep 17, 2008 at 11:10am
I am new to C++. I've read in section #include <string>
They said that we must #include <string> before using string data type, but it is still run when i do not put #include <string> line.

Please explain!

Thanks

Sep 17, 2008 at 11:52am
You might be including other header files that include string.
Sep 17, 2008 at 12:01pm
Here is my code:

#include <iostream>
using namespace std;
int main()
{
string str = "Hello World"; // I think i should error here with unknown data type
cout << str;

return 0;
}

thanks
Sep 17, 2008 at 12:27pm
Nope. No error. It seems iostream includes string as well. As simple as that.
Sep 17, 2008 at 3:36pm
I think your compiler is just being nice to you. <iostream> is not required (actually, it is not supposed to) #include <string>. If you using strings, you should #include <string>, whether or not your particular compiler lets you get away without it.
Sep 17, 2008 at 4:30pm
Just for the record, I was using MinGW, but Duoas is right. Don't depend on the particular headers to do the inclusion for you.
Sep 18, 2008 at 2:59am
I am using Dev-C++ 4.9.9.2. Yes, I get the point. However, can you explain more details? or link me the other resource on the web.
Sep 19, 2008 at 2:14am
I never noticed that.. I used the older version of dev c++ and it wouldn't allow that.

The compiler notices that you are using a 'string' variable type and automatically adds in the correct header file without you knowing. Its best practice to declare the headers and not to rely on the compiler to do it.

Here is some functions of the <string> header
http://www.cplusplus.com/reference/clibrary/cstring/

What exactly are you looking for? Reference to the header itself or why the compiler allows the string variable without the header file.
Sep 19, 2008 at 12:17pm
No, that is the C string library. The C++ string library is the one in question:

http://www.cplusplus.com/reference/string/

Sep 20, 2008 at 2:49am
My mistake, sorry.
Topic archived. No new replies allowed.