Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m cleaning up the includes in a C++ project I\'m working on, and I keep wonde

ID: 659001 • Letter: I

Question

I'm cleaning up the includes in a C++ project I'm working on, and I keep wondering whether or not I should explicitly include all headers used directly in a particular file, or whether I should only include the bare minimum.

Here's an example, Entity.hpp:

#include "RenderObject.hpp"
#include "Texture.hpp"

struct Entity {
    Texture texture;
    RenderObject render();
}
(Let's assume that a forward declaration for RenderObject is not an option.)

Now, I know that RenderObject.hpp includes Texture.hpp - I know that because each RenderObject has a Texture member. Still, I explicitly include Texture.hpp in Entity.hpp, because I'm not sure if it's a good idea to rely on it being included in RenderObject.hpp.

So: Is it good practice or not?

Explanation / Answer

You should always include all headers defining any objects used in a .cpp file in that file regardless of what you know about what's in those files. You should have include guards in all header files to make sure that including headers multiple times does not matter.

The reasons:

This makes it clear to developers who read the source exactly what the source file in question requires. Here, someone looking at the first few lines in the file can see that you are dealing with Texture objects in this file.
This avoids issues where refactored headers cause compilation issues when they no longer require particular headers themselves. For instance, suppose you realize that RenderObject.hpp doesn't actually need Texture.hpp itself.
A corollary is that you should never include a header in another header unless it is explicitly needed in that file.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote