Holly
Holly

Reputation: 1976

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.

Upvotes: 7

Views: 5731

Answers (3)

irobot
irobot

Reputation: 1024

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

Upvotes: 11

Michael Slade
Michael Slade

Reputation: 13877

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.

Upvotes: 0

LihO
LihO

Reputation: 42133

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?

Upvotes: 5

Related Questions