views:

111

answers:

3

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.

+3  A: 

This has nothing to do with design patterns. You would include B.h whenever you need to use the class B, and you would include A.h whenever you need to use the class A. If the class B is a design detail of class A, or otherwise closely associated with it, put it in A.h rather than in a separate header file.

anon
I'm happy I'm not the only one getting irked by people randomly using the design-patterns tag, just because the cool kids use it as well.
Matti Virkkunen
If you only use references or pointers to B, you don't necessarily have to include B.h - you could just forward-declare B.
sepp2k
@sepp2K Just because you can do something does not mean you should. And only having references or pointers toes not constitute using a class in my book.
anon
to Neil Butterworth: sorry for using unneccessary tag.to Matti: I was wrong, that is not just because etc. etc.sepp2K, yes, I know this, think like I use somebody's lib and can't change it.
Max
+6  A: 

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).

Michael Aaron Safyan
This answer is great as anything that makes dependancies clearer is to be applauded.N.B: The usage of include guards is a necessity.
Johnsyweb
A: 

I'd like to point out that when you do have header files, you should have a define to make sure it isn't included twice.

For example:

A.h:

#ifndef _A_H_
#define _A_H_

class A 
{
};

#endif

B.h:

#ifndef _B_H_
#define _B_H_

#include "a.h"

class B : public A
{
};

#endif

I think the above makes the most sense because now you can include A and B as many times as you think you'll need, but it won't be compiled multiple times.

Daniel
Those header guard names are illegal in C++ user code - they are reserved for the implementation.
anon