Forced to use forward declaration even though the

2019-06-02 21:42发布

问题:

I have a weird issue in a C++ code and I cannot figure out what is going on. I know what a forward declaration is, and I know when to use them etc...

However, in a C++ project I have, I am forced to foward declare a class that has been already declared in an included header. It looks something like this

windows.h:

#ifndef WINDOWS_HH_
#define WINDOWS_HH_

#include "foo.h"

class fooC;                 // If I don't forward declare here, won't compile!?
class WindowC
{
     public:
          WindowC();
          ~WindowC();
     public:
          fooC a;
};
#endif

and then, foo.h contains the declaration of fooC

#ifndef FOO_HH_
#define FOO_HH_
class fooC
{
     public:
            fooC();
            ~fooC();
};
#endif

Any idea why this might be happening? The actual code is part of a big project and it is really difficult to figure out what the error might be... but I am sure that theoretically that forward declaration of fooC shouldn't be necessary, should it?

回答1:

A common cause for such an effect would be a circular dependency between the header files.

Does foo.h include windows.h (maybe indirectly), creating a circular dependency?



回答2:

You need the full definition of fooC anyway, because it's included directly (not by pointer or reference) in WindowC. Like @joval said, it shouldn't be necessary. What kind of compiler error are you getting? I'd look for simple mistakes like forgetting include guards or semicolon after class definitions.



标签: c++ class