3

Lets say I have 2 classes. One is BaseClass and one is DerivedClass, being a derived class of BaseClass. I need to be able to create objects of both classes in another file. By using an #include statement to include the derived class in the new file, I have access to the derived class directly and the base class indirectly (as the derived class includes it in its file). Is it better to use this method of indirect "access" to the base class, or would it be better to directly include it alongside the derived class in the file?

Niall
  • 30,036
  • 10
  • 99
  • 142
JosephTLyons
  • 2,075
  • 16
  • 39

2 Answers2

5

The general advice is include what you use.

If you are coding to an API specification, and that specification does not explicitly detail the base-derived nature of the classes, then any changes to that relationship may break the includes that the files you depend on use.

See here as well.

If you are certain the BaseClass will always the base to the DerivedClass, then there may be little need include both, but for clarity, I would go ahead and do it anyway, it shows your intent.

Niall
  • 30,036
  • 10
  • 99
  • 142
  • That makes total sense. And while I wrote both classes and know that I they won’t change in that respect, it seems to make more sense to include it directly. – JosephTLyons Feb 13 '18 at 07:41
  • 1
    Worth mentioning is that you should always use header guards. – Ron Feb 13 '18 at 07:42
  • 2
    Worth noting that with include guards the impact of multiple includes of the same file can be miniscule. – user4581301 Feb 13 '18 at 07:42
  • I am not so sure of that: even with #ifndef #define the preprocessor still has to parse the entire file to find the #endif – Picaud Vincent Feb 13 '18 at 07:52
3

Including all needed headers instead of relying on transitivity gives has two advantages:

  1. If your header files will be refactored, you will not need to change your cpp file.

  2. It clearly identifies your intent for other developers.

Yola
  • 18,496
  • 11
  • 65
  • 106