Header file inclusion question

Looking for what's considered good practice here. Let's say I have..

1
2
3
4
5
6
7
8
9
10
file: classA.h

#pragma once
#include <string>

classA
{
  public:
  std::string _string;
};



1
2
3
4
5
6
7
8
9
10
11
12
file: classB.h

#pragma once
#include "classA.h"
#include <string> // <--- Include this again even though classA.h is included and uses <string>?

classB
{
  public:
  classA _obj;
  std::string _string;
};


So I have a little class here that uses an std::string (classA), so it includes the <string> header. Now let's say I have another file that wants to make an instance of object A (classB), but also wants to use an std::string of it's own. Would I #include <string> again in this new file, even though it's being included recursively through the classA.h file?


And since we're on the topic. Let's say I have multiple classes that include the same thing. let's say I have 5 different classes that are all including <string>, <cassert>, <stdio.h>, and <memory>. Would it make any sense to have an "includes.h" file that includes all 4 of those same libraries, and then just use #include "includes.h" in all the files that want those? Or will that lead to trouble?
Last edited on
Would I #include <string> again in this new file
Yes, you should, although if you don't include it it's alright also.

let's say I have 5 different classes that are all including <string>, <cassert>, <stdio.h>, and <memory>. Would it make any sense to have an "includes.h" file that includes all 4 of those same libraries, and then just use #include "includes.h" in all the files that want those? Or will that lead to trouble?
No, having an includes.h file like you're describing would be pointless. You can do if you want, you it won't give you any benefits.
However there's a mechanism known as precompiled headers (PCH) which on some compilers functions similarly to how you're describing. PCHs are used to reduce compilation time. But you have to explicitly tell the compiler to use them, and just including a bunch of headers in a header is not enough. Check your compiler's documentation if you want to learn more.
@helios Appreciate the reply. I knew it would still work, I just figured if I'm gonna use C++ I may as well make use of it's performance and utilize preferred / good practices when doing things. Wasn't sure if that extra include of the same library created a significant footprint or not.
Last edited on
It would definitely be wrong to leave the include out of classB.h. What if you changed classA.h so it didn't use string anymore? B should know as little as possible about the details of A.
Last edited on
@tpb Alright, good to know. Thank you!
Topic archived. No new replies allowed.