How does this program compile?

See the following code sample:
1
2
3
4
5
6
7
8
9
10
#include <iostream>

using namespace std;

int main()
{
    string hello = "Hello world!";   
    cout << hello;
    return 0;
}


Notice how I used std::string without including the <string> header file. How is that? Isn't the std::string defined in the string header file?

I run Linux Mint 16, based on Ubuntu 13.10 (the magic of LinuxID[ http://sourceforge.com/p/linuxid ] !), with g++ 4.8.1
It's not guaranteed. The standard headers *might* include other standard headers, but you cannot rely on this. On some compilers this code will not compile.
I found this question interesting, so I started searching in the deeper files of my compiler (mingw-g++). I had to go very deep before I found the anwser, but I found it. It works like this:

The iostream includes the istream.
The istream includes the ios.
The ios includes bits/ios_base.h
ios_base.h includes bits/locale_classes.h
locale_classes.h includes string

And string defines the std::string. So I guess this is how it works. I'm not 100% sure though, but it does look logical in some way.

Looking through string I find a lot of includes to other bits headers. So I guess the std::string is defined somewhere deeper in there.
> I guess this is how it works. I'm not 100% sure though, but it does look logical in some way.

Shadowwolf +1
http://www.cplusplus.com/forum/beginner/109609/#msg597665


> http://www.cplusplus.com/forum/lounge/107071/#msg580112

That is a quirk of one particular version of one particularly poor implementation the standard C++ library.
http://coliru.stacked-crooked.com/a/d16a45684789e7af
http://rextester.com/XOTTU65830
Is this accidental, or is it just a hidden feature?
Neither really. It's a choice of the particular implementation.

As LB said, this behavior is not guaranteed. Other implementations may be (probably will be) different.

Bottom line, if you use std::string, include the header. No harm in doing so if other headers have already included it.
@AbstractionAnon Well, I was just curious, and I gained new info: I would never know, and few people do, that header #include d other header files!
Headers almost always include other headers, and most people know this. For example if you were designing a class that had a function taking a std::string parameter, in the class header you would have to include the string header.
Is this accidental, or is it just a hidden feature?


That depends on how you think about it.

Including the header <iostream> is required, by the C++ standard, to make the definition of the class std::basic_string<char> visible (although the requirement is somewhat obscure)

It does not require exposing the typedef std::string or any other part of the header <string> (such as std::getline or operator< for strings).
Last edited on
Topic archived. No new replies allowed.