I am a beginner with C++. When I write the code sometimes I write #include <string>
and the code works, other times I don't write #include <string>
and the code doesn't work. But sometimes it works without #include <string>
.
So do I have to write #include <string>
so that the code works?
It is not true that the header string is included by other headers. The header string itself only has includes. No Definitions. So all necessary definitions needed for the usage of string are in headers included by the header string. These headers may already be included by other headers. Then everything works. The header ios for example includes stringbuf, which includes ...
If you use members that are declared inside the standard header
string
then yes, you have to include that header either directly or indirectly (via other headers).Some compilers on some platforms may on some time of the month compile even though you failed to include the header. This behaviour is unfortunate, unreliable and does not mean that you shouldn’t include the header.
The reason is simply that you have included other standard headers which also happen to include
string
. But as I said, this can in general not be relied on and it may also change very suddenly (when a new version of the compiler is installed, for instance).Always include all necessary headers. Unfortunately, there does not appear to be a reliable online documentation on which headers need to be included. Consult a book, or the official C++ standard.
For instance, the following code compiles with my compiler (
gcc
4.6):But if I remove the first line, it no longer compiles even though the
iostream
header should actually be unrelated.It is possible that other headers that you do include have
#include <string>
in them.Nonetheless, it is usually a good idea to
#include <string>
directly in your code even if not strictly necessary for a successful build, in case these "other" headers change - for example because of a different (or different version of) compiler / standard library implementation, platform or even just a build configuration.(Of course, this discussion applies to any header, not just
<string>
.)Although, there is no direct occurence of
#include <string>
in a particular source file, doesn't mean it hasn't been included by another header file. Consider this:File:
header.h
File:
source1.cc
File:
source2.cc
File:
source3.cc
If you're just using a pointer/reference to a user defined type, the type only needs to be declared:
But when you're using the value, the compiler needs to know the size and with that the definition of the type.
And keep in mind that standard headers may include other ones, which doesn't automaticly mean that all implementations do that, so you can't rely on that.