Question

Somewhat similar situation to what was asked here.

I've got a class A that has a member pointer to class B.

//A.h
class B;
class A {
    B *b;
public: 
    B *GetB();
};

B is defined in its own file.

Now, whenever I include A.h and want to access an A's b member, I also have to include B.h. In the case where both A and B have rather large headers (think old nasty legacy code) is it better to continue including both headers whenever I include one or to just have A.h include B.h and be done with it?

The headers are pretty large but most of our code requires both anyway, I'm just curious if there is some kind of design pattern that decides what is the best decision to make in this case.

Was it helpful?

Solution

This is opinion, of course. For me, it boils down to whether it makes sense to use A without B. If A has a ton of operations and only one of them involves B, then no, I wouldn't include B.h. Why should someone who only calls A.Foo() and A.Bar() need to pay the overhead of including an extra header?

On the other hand, if A is a B factory (for example) and you can't imagine anyone using it and not using B too, then maybe it makes sense to include B.h in A.h.

And if A had a member variable of type B (not B*) with the consequence that anyone who included A.h would have to include B.h too in order to compile, then I would definitely include it in A.h.

OTHER TIPS

wrap your header files with preprocessor to make sure they will be included only 1 time..

on B.h define

#ifndef __B_HEADER__
#define __B_HEADER__

.... B header files goes here....

#endif

then on A.h define

#ifndef __A_HEADER__
#define __A_HEADER__

#include <B.h>

.... A header files goes here....

#endif

and then include only A.h when it needs.

i personally prefer to include header files of what i know and want to use - i don't want to be bothered by the dependendcy tree of the components i use.

think when you include <iostream> in C++ STD library - do you really want to know and include explicitly all the <iostrem> dependencies (if there are)?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top