0

I have read the helpful article "When to use forward declaration?".

However, I am left with one a question. In the case were I can use a forward declare in the header, but not in the cpp is there a benefit and what is it?

Community
  • 1
  • 1
user870130
  • 565
  • 1
  • 8
  • 16

1 Answers1

2

The benefit is reduced dependencies on your header files. Whenever, you do a #include, the preprocessor basically adds that file into your header for compilation, this is called a dependency because your header needs it. So in large projects whenever the included file changes, the header file, its cpp file and everything which includes it also needs to be recompiled. Reducing dependencies generally can help reduce compile times in large projects.

Additionally, sometimes it is a requirement to break circular dependencies, which can often be found in sizable projects, e.g., file A includes file B, which includes file A again. So this is an added benefit of forward declaration.

pippin1289
  • 4,861
  • 2
  • 22
  • 37
  • 2
    it also breaks circular dependencies. Like 'struct a' needing to use `struct b` pointers and `struct b` needing `struct a` defined. – KitsuneYMG Mar 07 '14 at 16:11
  • This article ["Another Reason to Avoid #includes in Headers"](http://blog.knatten.org/2012/11/09/another-reason-to-avoid-includes-in-headers/) helped me understand why adding a #include to a header is not the same as adding it to the cpp file. – user870130 Mar 07 '14 at 17:17