Including .h files

Suppose I have two .h files: Ah and Bh Also, Ah includes Bh itself:

Bh - defines class B.

class B {
  ...
};

      

Ah - 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 classes A and B (class B can be used not only in A :: SomeFunction (B))

What are the pros for including both Ah and Bh (not just Ah) in terms of template design and coding style.

+2


a source to share


3 answers


Including both "Ah" and "Bh" makes the dependencies completely clear. There is no reason why "Ah" cannot have class B forward declared, and so including both headers prevents your ".cpp" file from breaking if transient variables are changed into a forward declaration. In general, you shouldn't rely on transient inclusions, and instead explicitly include all direct dependencies. (Note that this does not apply to "master include" headers, which are intended to provide transitive inclusions).



+6


a source


It has nothing to do with design patterns. You would include Bh when you needed to use class B, and you would include Ah when you need to use class A. If class B is a part of the construction of class A, or otherwise closely related to it, put it in Ah and not in a separate header file.



+3


a source


I would like to point out that when you have header files you should have a definition to make sure it is not included twice.

For instance:

hijri:

#ifndef _A_H_
#define _A_H_

class A 
{
};

#endif

      

Bh:

#ifndef _B_H_
#define _B_H_

#include "a.h"

class B : public A
{
};

#endif

      

I think the above makes sense because you can now include A and B as many times as you see fit, but it won't compile multiple times.

0


a source







All Articles