开发者

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

I've been looking at the Fear SDK for my university project, but have noticed some code like so:

Foo.h

class Foo
{
    public:
        int iSomething;
};

Bar.cpp:

#include "Foo.h"

// Forward declarations
class Foo;

Is there any particular reason to forward declare AND include the appropriate header in the same cpp file? Or is the forward declaration redundant because the header is being included?

EDIT:

Every time that I have s开发者_C百科een it in the code, the include statement is always before the forward declaration.


It's more than simply redundant, it's potentially problematic. Say Foo.h changes so Foo becomes a typedef to some particular instantiation of a generic, templatised equivalent - the kind of thing that can be anticipated as part of normal software evolution. Then Bar.cpp's "class X" will needlessly cause a compilation error ala:

--- 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 reason I always recommend using dedicated forward-declaration headers ala <iosfwd>, maintained with and included by the main header to ensure ongoing consistency. I never put "class X;" in an implementation file unless the class is defined in there too. Remember that the seeming benefits of "class X;" forward declarations is not so much that they avoid an #include, and more that the files they include can be large and in turn include a lot of other files: dedicated forward-declaration headers typically avoid the overwhelming majority of that anyway.


If the forward declaration came before the includes, it might eliminate a dependency. Coming after the actual .h file that defines it does nothing.


The original class Foo; may have been vestigial.

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

Without seeing the code, I'd hazard the guess 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 compile time. compile time is not a problem when it takes a second, but when projects take an hour to build every second helps :)


The forward declaration is redundant, but also quite harmless. Maybe the author uses a lot of forward declarations, and doesn't rigorously ensure they are always required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜