c++header-filesforward-declaration

Forward declaration / when best to include headers?


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.


Solution

  • 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