22

Here is my code:

#include <iostream>

int main(int argc, char const *argv[])
{
    std::string s = "hello";
    std::cout << s.size() << std::endl;
    return 0;
}

To my surprise, I can compile and run it with clang++, though I even don't add #include <string>.

So, is it necessary to add #include <string> in order to use std::string ?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
chenzhongpu
  • 6,193
  • 8
  • 41
  • 79

4 Answers4

26

Your implementation's iostream header includes string. This is not something which you can or should rely on. If you want to use std::string, you should always #include <string>, otherwise your program might not run on different implementations, or even in later versions of your current one.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
10

In short: yes, it is necessary.

Parts of standard library often use other parts, so <string> was included somehow through <iostream>, and your code compiles nicely.

If you accidentally decide that you don't need <iostream> anymore and remove that include, <string> will be implicitly removed, too, and you get a confusing compilation error. That's why it is a good practice to put all necessary includes.

lisyarus
  • 15,025
  • 3
  • 43
  • 68
5

Some header might include other headers, but that's an implementation issue and not something you can count on. Always explicitly include the headers you need.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

iostream includes <string>. It ripples through.

Well actually that's implementation dependant and not a guarantee. You should explicitly include the headers you need.

Nathan Cooper
  • 6,262
  • 4
  • 36
  • 75