0

I'm new in c++ world, and learned that it is a good practice to make forward declarations. But is it always good?

I'm looking for guidelines for when it is a good practice to make a forward declaration and when it is not good, but I really couldn't find any. There are any objective case for when it should be used or not, or it is entirely up to the developer?

SirGuy
  • 10,660
  • 2
  • 36
  • 66
AlexVanAxe
  • 68
  • 5
  • 3
    In general, use it when you don't need a full class definition. – juanchopanza May 29 '14 at 14:00
  • @πάνταῥεῖ Unfortunately, despite the title, the possible duplicate asks a different question (when *can* I use a fwd decl, not when *should* I.) I edited the title to reflect that. – juanchopanza May 29 '14 at 14:02

2 Answers2

2

As mentioned by juanchopanza, in general you can use forward declarations when you don't need a full class definition - basically when you don't need to know the size or members of the class in question. It allows you to remove compile-time dependencies, which can simplify and speed-up compilations.

For example, if you only use pointers to a class, then you don't need to know any more about it. However, if you call a method of that class, or store an actual instance of it, then you need to know the full details of the class.

class A;  // forward declaration

class B {
    ...
    void func1(A*);
}

class C {
    ...
    A m_inst;
}

In the above, C will not compile, as it needs to know the size of A at the point of declaration. However, func1 is fine, as it only uses a pointer to A, so doesn't need to know size or implementation.

Herb Sutter has a bit of information along with explanations, although be warned that some of it is a little advanced if you're a beginner.

Boumbles
  • 2,473
  • 3
  • 24
  • 42
icabod
  • 6,992
  • 25
  • 41
1

There can be cases where you actually start complicating your code base with otherwise unnecessary applications of the PIMPL idiom (which involves forward declarations) to reduce compilation time when in fact you do not have any compilation speed problems in the first place, at least with that particular class or header file.

This can then be considered a case of premature optimisation and a misuse of forward declarations.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62