Search code examples
c++classincludecode-readability

Should I include files included in another header?


Most often when creating multiple classes inside a program that use each other, I like to include only the minimum number of header files I need to reduce clutter.

For example, say class C inherits from class B, which contains class A. Now of course since class B contains class A as a member, it needs to include a.h in b.h. However, let's say C also needs to include a.h. Being lazy as I am, I just include b.h (which C needs to include anyways), and since b.h already includes a.h, I don't need to include anything more, and it compiles fine. Same for my .cpp files: I just include the header, and anything that's included in the header will be automatically included in my .cpp file, so I don't include it there.

Is this a bad habit of mine? Does it make my code less readable?


Solution

  • Include what's necessary for the header file to be parsed without relying on external include ordering (in other words : make your headers self-sufficient).

    In your case, if c.h declares a class C which inherits from class B, obviously you must include B.h. However, if class A never appears in c.h, I believe there is no reason to include it. The fact that b.h mentions A means that b.h must make what's necessary to be parsed, either through forward declaring A or including a.h.

    So from my point of view, you're doing what should be done.

    Also note that if for some reasons c.h starts mentioning A, I would add the appropriate include or forward declaration so I wouldn't depend on the fact that b.h does it for me.