Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

including .h files

Suppose I have two .h files: A.h and B.h. Moreover, A.h includes B.h itself:

B.h - defines class B.

class B {
  ...
};

A.h - defines class A, which uses class B.

#include B.h

class A {
  void SomeFunction(const B& b);
};

Now, I have some .cpp file, that uses both A and B classes (B class maybe used not only in A::SomeFunction(B))

What are the pluses to include both A.h and B.h (instead of only A.h) from the perspective of design-patterns and coding style.

like image 403
Max Avatar asked Jul 13 '26 20:07

Max


1 Answers

Including both "A.h" and "B.h" makes the dependencies completely clear. There is no reason why "A.h" could not have forward-declared class B, and so including both headers prevents your ".cpp" file from breaking should the transitive include be changed to a forward declaration. In general, it is not a good idea to rely on transitive includes, and instead one should explicitly include all direct dependencies. (Note that this does not apply for "master include" headers that are intended to give transitive includes).

like image 140
Michael Aaron Safyan Avatar answered Jul 17 '26 19:07

Michael Aaron Safyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!