Why include a header and forward to declare a class contained in the same cpp file?

I looked at the Fear SDK for my university project, but noticed this code:

foo.h

class Foo { public: int iSomething; }; 

Bar.cpp:

 #include "Foo.h" // Forward declarations class Foo; 

Is there any specific reason to forward the AND declaration and include the appropriate header in the same cpp file? Or a redundant ad ahead because the headline is included?

EDIT:

Every time I saw it in code, the include statement is always before the forward declaration.

+5
c ++ header forward-declaration
source share
4 answers

This is more than just redundant; it is potentially problematic. Let's say Foo.h changes, so that Foo becomes typical of a particular instance of a universal, templatised equivalent - the kind of thing you would expect as part of a normal software evolution. Then Bar.cpp "class X" will be useless to cause ala compilation error:

 --- fwd.h --- template <typename T> class XT { public: int n_; }; typedef XT<int> X; --- fwd.cc --- #include "fwd.h" class X; int main() { X x; x.n_ = 0; return x.n_; } --- compilation attempt --- ~/dev .../gcc/4.1.1/exec/bin/g++ fwd.cc -o fwd fwd.cc:3: error: using typedef-name 'X' after 'class' fwd.h:8: error: 'X' has a previous declaration here 

This is one of the reasons I always recommend using the forward ala <iosfwd> highlighted declaration headers, which are supported and included in the main header to ensure consistent consistency. I never put "class X"; in the implementation file if the class is not defined in it. Remember that the apparent benefits are β€œclass X”; advanced declarations are not so much that they avoid #include , and moreover, the files that they include can be large and, in turn, include many other files: the highlighted direct declaration headers usually avoid the vast majority of them.

+6
source share

If a direct ad appears before inclusion, it can eliminate the dependency. After the actual .h file that defines it, it does nothing.

+3
source share

Original class Foo; may have been rudimentary.

Remember that if the source uses pointers only for the Foo class [and does not actually try to create Foo objects or Foo pointers for dereferencing], you do not need to define the class before using it.

Without seeing the code, I would jeopardize that the original version of bar.cpp had code that did not require the definition of foo

I use forward declarations in large projects to reduce compilation time. compilation time is not a problem when it takes a second, but when projects take an hour to build every second, it helps :)

+2
source share

Forward declaration is redundant, but also completely harmless. Perhaps the author uses many advanced declarations and does not guarantee that they are always required.

+1
source share

All Articles