I am wondering if there is any drawback for using forward declarations in all places when possible. This is if my header contains only declarations.
As far as I understand, using forward declaration speeds up compile time, but I don't know of any drawbacks as such.
a.h:
Class A
{
};
b.h:
// Should I use and include "a.h" in the cpp file (e.g., a.cpp)
Class A;
Class B
{
doSomething(A *a);
A *myA;
};
Or is it better to use
b.h:
#include "a.h"
Class B
{
doSomething(A *a);
A *myA;
};
Using forward declarations improves decoupling. If you can avoid including "A.h"
by using a forward declaration, it is a good idea to use forward declaration. It is better not only because your builds run faster (after all, preprocessed headers can deal with compiler efficiency pretty well) but because it tells the readers of your declaration that the structure of your class B
does not depend on knowing anything about your class A
, other than that it exists*.
EDIT (to answer your question) The only downside to forward declarations that I know is that you cannot use them in all situations: for example, a declaration similar to this:
class B
{
A myA[10];
};
would not compile, because the compiler needs to know the size of A
. However, the compiler finds such issues very reliably, and informs you about them in unambiguous terms.
* The implementation of class B
could very well depend on knowing the details of class A
. However, this dependency becomes an implementation detail of B
hidden from the users of your class; you can change it at any time without breaking the code dependent upon class B
.