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.
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.
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)?
Related
I understand if a.h includes b.h and I don't declare anything from b.h in my header including only a.h is good practice. If I were to declare anything from b.h in my header then I should include both a.h and b.h to make my header self-sufficient.
In my header I do declare both class A from a.h and class B from b.h. However, class A depends on class B, so I always use them together. I never use class B independently of class A. In this case does it still make sense to include both a.h and b.h?
a.h
#include "b.h"
#include <queue>
class A
{
private:
std::queue<B> mFoo;
}
In my actual code I think it makes my intention clearer when I include just my event system for example and not a number of includes that seem superfluous to me.
You should always include direct dependencies: if a depends directly on b and c, even if b already includes c, a should include both.
Be explicit about your dependencies. You should not rely on the fact that some other module already depends on the module you'd have to include. You never know how the dependency tree will change in the future.
In this regard, having implicit dependencies makes your code fragile.
To make sure you don't redefine something by including it twice, you can put header guard inside your header files:
#ifndef GRANDFATHER_H
#define GRANDFATHER_H
struct foo {
int member;
};
#endif /* GRANDFATHER_H */
You could also use
#pragma once
But not every compiler supports it.
That way even if the preprocessor will step on same include more than once, It won't re-include the code.
My rule: Given some random header foo.h, the following should compile clean, and preferably should link and run as well:
#include "foo.h"
int main () {}
Suppose foo.h doesn't contain any syntax errors (i.e., a source file that includes it in the context you intended compiles clean) but the above nonetheless doesn't compile. This almost always means there are some missing #include directives in foo.h.
What this doesn't tell you is whether all of the headers included in foo.h truly are needed. I have a handy little script that checks the above. If it passes, it creates a copy of foo.h and progressively comments out #include directives and sees if those modified versions of foo.h pass the above test. Any that do pass are indicative of suspect superfluous #include directives.
The problem is that the #include directives deemed to be superfluous might not be superfluous. Suppose foo.h defines class Foo, which has data members of type Bar and Baz (not pointers, members). The header foo.h correctly includes both bar.h and baz.h because that is where those two classes are defined. Suppose bar.h happens to include baz.h. As the author of foo.h, I don't care. I should still include both of those headers in foo.h because foo.h has direct dependencies on both of those other headers. My script will complain about suspect superfluous headers in this case. Those complaints are hints, not mandates.
On the other hand, fixing foo.h so that my simple test program above compiles clean is a mandate.
I'm pretty clear on when I can/can't use forward declaration but I'm still not sure about one thing.
Let's say I know that I have to include a header sooner or later to de-reference an object of class A.
I'm not clear on whether it's more efficient to do something like..
class A;
class B
{
A* a;
void DoSomethingWithA();
};
and then in the cpp have something like..
#include "A.hpp"
void B::DoSomethingWithA()
{
a->FunctionOfA();
}
Or might I as well just include A's header in B's header file in the first place?
If the former is more efficient then I'd appreciate it if someone clearly explained why as I suspect it has something to do with the compilation process which I could always do with learning more about.
Use forward declarations (as in your example) whenever possible. This reduces compile times, but more importantly minimizes header and library dependencies for code that doesn't need to know and doesn't care for implementation details. In general, no code other than the actual implementation should care about implementation details.
Here is Google's rationale on this: Header File Dependencies
When you use forward declaration, you explicitly say with it "class B doesn't need to know anything about internal implementation of class A, it only needs to know that class named A exists". If you can avoid including that header, then avoid it. - it's good practice to use forward declaration instead because you eliminate redundant dependencies by using it.
Also note, that when you change the header file, it causes all files that include it to be recompiled.
These questions will also help you:
What are the drawbacks of forward declaration?
What is the purpose of forward declaration?
Don't try to make your compilation efficient. There be dragons. Just include A.hpp in B.hpp.
The standard practice for C and C++ header files is to wrap all of the header file in an #ifndef to make sure it is compiled only once:
#ifndef _A_HPP_
#define _A_HPP_
// all your definitions
#endif
That way, if you #include "A.hpp" in B.hpp, you can have a program that includes both, and it won't break because it won't try to define anything twice.
Most often when creating multiple classes inside a program that use each other, I like to include only the minimum number of header files I need to reduce clutter.
For example, say class C inherits from class B, which contains class A. Now of course since class B contains class A as a member, it needs to include a.h in b.h. However, let's say C also needs to include a.h. Being lazy as I am, I just include b.h (which C needs to include anyways), and since b.h already includes a.h, I don't need to include anything more, and it compiles fine. Same for my .cpp files: I just include the header, and anything that's included in the header will be automatically included in my .cpp file, so I don't include it there.
Is this a bad habit of mine? Does it make my code less readable?
I stick with this simple rule: include everything you need to completely declare a given class, but not more and make no assumptions about includes being pulled in from other sources, i.e. ensure your files are self-sufficient.
Include what's necessary for the header file to be parsed without relying on external include ordering (in other words : make your headers self-sufficient).
In your case, if c.h declares a class C which inherits from class B, obviously you must include B.h. However, if class A never appears in c.h, I believe there is no reason to include it. The fact that b.h mentions A means that b.h must make what's necessary to be parsed, either through forward declaring A or including a.h.
So from my point of view, you're doing what should be done.
Also note that if for some reasons c.h starts mentioning A, I would add the appropriate include or forward declaration so I wouldn't depend on the fact that b.h does it for me.
It's best to include every header with definitions that you are using directly.
Relying on one of the other headers to include stuff makes your code more fragile as it becomes dependent on the implementation of classes that are external to it.
EDIT:
A short example:
Class B uses class A, e.g. a hash table implementation B that uses a hashing mechanism A
You create a class C that needs a hash table (i.e. B) and a hash algorithm (i.e. A) for some other purpose. You include B.h and leave out A.h since B.h includes it anyway.
Mary, one of your co-workers, discovers a paper about this new fabulous hashing algorithm that reduces the probability of collisions, while it needs 10% less space and is twice as fast. She (rightly) rewrites class B to use class D, which implements that algorithm. Since class A is no longer needed in B, she also removes all references to it from B.h.
Your code breaks.
EDIT 2:
There are some programmers (and I've occasionally been guilty of this too, when in a hurry) who deal with this issue by having an "include-all" header file in their project. This should be avoided, since it causes namespace pollution of unparalleled proportions. And yes, windows.h in MSVC is one of those cases in my opinion.
I'm using #pragma once, not #include guards on all my h files. What do I do if a.h needs to #include b.h and b.h needs to #include a.h?
I'm getting all sorts if errors because by doing this, the pragma once takes effect and one of them is missing each other. How should I do this.
Thanks
You need to forward declare the definitions you need. So if A uses B as a parameter value, you need to forward declare B, and vice versa.
It could be that just forward declaring the class names:
class A;
class B;
solves your problems.
The accepted answer to this question provides some additional guidance.
One possibility is to refactor some portion of the files a.h and b.h into a third file say c.h, and include it from both a.h and b.h. This way, the latter two would no longer need to mutually include each other.
Another possibility is to merge the separate header files into one.
A third possibility is the situation when two classes legitimately need to refer to each other. In such cases you have to use pointers. Moreover, you can forward declare the class instead of including its header file. [Mentioned also by jdv] For example,
// file a.h
struct B;
struct A { B * b_ };
// file b.h
struct A;
struct B { A * a_; };
However, without knowing your particular situation it is difficult to provide specific suggestion.
It depends on what is needed from each other's header file. IF it's a class definition, but it only is using a pointer to the class, then instead of including the head file just put in a forward declaration like:
class MyClassA;
The solution for this issue is 'forward declaration'.
If you have a class or a function that needs to be used in 2 headers one of the headers needs to forward declare the used class or type.
Or you need to consider to restructure your headers.
This is a common beginner issue that circular dependencies are causing such issues. If you google on 'forward declaration' will find tons of results.
Since your question was too unspecific I can't give you an exact answer, sorry for this.
You can not use incomplete types, but you can just forward declare them. You just tell the compiler:"Don't get syntax errors, I know what i am doing". Which means that the linker will go and find complete types from libraries whatsoever.
C++ headers
If I have A.cpp and A.h as well as b.h, c.h, d.h
Should I do:
in A.h:
#include "b.h"
#include "c.h"
#include "d.h"
in A.cpp:
#include "A.h"
or
in A.cpp:
#include "A.h"
#include "b.h"
#include "c.h"
#include "d.h"
Are there performance issues? Obvious benefits? Is something bad about this?
You should only include what is necessary to compile; adding unnecessary includes will hurt your compilation times, especially in large projects.
Each header file should be able to compile cleanly on its own -- that is, if you have a source file that includes only that header, it should compile without errors. The header file should include no more than is necessary for that.
Try to use forward declarations as much as possible. If you're using a class, but the header file only deals with pointers/references to objects of that class, then there's no need to include the definition of the class -- just use a forward declaration:
class SomeClass;
// Can now use pointers/references to SomeClass
// without needing the full definition
The key practice here is having around each foo.h file a guard such as:
#ifndef _FOO_H
#define _FOO_H
...rest of the .h file...
#endif
This prevents multiple-inclusions, with loops and all such attendant horrors. Once you do ensure every include file is thus guarded, the specifics are less important.
I like one guiding principle Adam expresses: make sure that, if a source file just includes a.h, it won't inevitably get errors due to a.h assuming other files have been included before it -- e.g. if a.h requires b.h to be included before, it can and should just include b.h itself (the guards will make that a noop if b.h was already included previously)
Vice versa, a source file should include the headers from which it is requiring something (macros, declarations, etc), not assume that other headers just come in magically because it has included some.
If you're using classes by value, alas, you need all the gory details of the class in some .h you include. But for some uses via references or pointers, just a bare class sic; will suffice. E.g., all other things being equal, if class a can get away with a pointer to an instance of class b (i.e. a member class b *my_bp; rather than a member class b *my_b;) the coupling between the include files can be made weaker (reducing much recompilation) -- e.g. b.h could have little more than class b; while all the gory details are in b_impl.h which is included only by the headers that really need it...
What Adam Rosenfield told you is spot on. An example of when you can use a forward declaration is:
#ifndef A_H_
#define A_H_
#include "D.h"
class B; //forward declaration
class C; //forward declaration
class A
{
B *m_pb; //you can forward declare this one bacause it's a pointer and the compilier doesn't need to know the size of object B at this point in the code. include B.h in the cpp file.
C &m_rc; //you can also forware declare this one for the same reason, except it's a reference.
D m_d; //you cannot forward declare this one because the complier need to calc the size of object D.
};
#endif
Answer: Let A.h include b.h, c.h and d.h only if it's needed to make the build succeed. The rule of thumb is: only include as much code in a header file as necessary. Anything which is not immediately needed in A.h should be included by A.cpp.
Reasoning: The less code is included into header files, the less likely you will need to recompile the code which uses the header file after doing some change somewhere. If there are lots of #include references between different header files, changing any of them will require rebuilding all other files which include the changed header file - recursivel. So if you decide to touch some toplevel header file, this might rebuild huge parts of your code.
By using forward declarations wherever possible in your header files, you reduce the coupling of the source files and thus make the build faster. Such forward declarations can be used in many more situations than you might think. As a rule of thumb, you only need the header file t.h (which defines a type T) if you
Declare a member variable of type T (note, this does not include declaring a pointer-to-T).
Write some inline functions which access members of an object of type T.
You do not need to include the declaration of T if your header file just
Declares constructors/functions which take references or pointers to a T object.
Declares functions which return a T object by pointer, reference or value.
Declares member variables which are references or pointers to a T object.
Consider this class declaration; which of the include files for A, B and C do you really need to include?:
class MyClass
{
public:
MyClass( const A &a );
void set( const B &b );
void set( const B *b );
B getB();
C getC();
private:
B *m_b;
C m_c;
};
You just need the include file for the type C, because of the member variable m_c. You can often remove this requirement as well by not declaring your member variables directly but using an opaque pointer to hide all the member variables in a private structure, so that they don't show up in the header file anymore.
Prefer not including headers in other headers - it slows down compilation and leas to circular reference
There would be no performance issues, it's all done at compile time, and your headers should be set up so they can't be included more than once.
I don't know if there's a standard way to do it, but I prefer to include all the headers I need in source files, and include them in the headers if something in the header itself needs it (for example, a typedef from a different header)