Include in header file vs. forward-declare and include in .cpp

colddie picture colddie · Apr 5, 2013 · Viewed 21.4k times · Source

I have a class B, and I want to call members form class A. So:

1.

//A.h    
class B; 
class A 
{ 
private:
    B* m_p; 
}; 

//a.cpp
#include "B.h"

2.

// A.h
#include "B.h"

class A 
{ 
private: 
    B * impl_; 
}; 

which way is better and is this two similar when a small project with not too much dependence involves?

Answer

jogojapan picture jogojapan · Apr 5, 2013

Your first way of doing it means that in a.h, the existence of class B is known, but not its definition. This limits what you can do with B inside a.h. For example, you can have variables of type B *, but not variables of type B (because for a declaration of a variable of type B the compiler must be able to see the full definition of B). Also, if you have variables of type B *, you can't dereference the pointer (because for that, too, the definition of B must be known).

Therefore, your second choice – which doesn't have these problems – is preferred, and this is what most people use most of the time.

It's only special cases in which the first method may be useful. For example:

  • If the .h files include each other (but then you may get a number of further problems, also regarding include-guards; this is generally difficult and to be avoided);
  • If b.h is extremely large and complex, so you'd like to avoid including it wherever possible because it slows down the compilation process.