Base class has incomplete type - why?

in my game I wanted to create a “base” scene and few extending it.

Something like this:


#ifndef GameScene_hpp
#define GameScene_hpp

#include "cocos2d.h"


class GameScene : public cocos2d::Layer
    virtual bool init();

#endif /* GameScene_hpp */


#ifndef FarmScene_hpp
#define FarmScene_hpp

#include "cocos2d.h"
#include "GameScene.h"


class FarmScene : public GameScene
    static cocos2d::Scene* createScene(int gameIndex);
    virtual bool init();
#endif /* FarmScene_hpp */

Compiles fine.

But when I’m adding #include "FarmScene.h into AppDelegate.h I’m getting the following error in FarmScene:

class FarmScene : public GameScene <-- Base class has incomplete type

Moving include from above to AppDelegate.cpp resolved the problem.
But why is it happening in the first place? I’m always importing everything in .h file, not in .cpp. #ifdef should protect class to be imported more than once, so where’s the problem?

I think it is the CREATE_FUNC. I have seen this before. Just stop using it and make your own constructors.

Try forward declaring only what you need in AppDelegate.h. In this case, it looks like you need to forward declare the class FarmScene. Then #include the FarmScene header in your AppDelegate.cpp file.

If your AppDelegate header relies on your FarmScene implementation, either remove that (e.g. you declare a FarmScene by value, change it to a reference or pointer) or push it to your AppDelegate.cpp file (e.g. you have code in your header that accesses a FarmScene member or method, move that to the cpp file). At least for now until you can figure out exactly why you’re getting your compilation error.

As a general rule, try to include only what you need in header files. So if you don’t need a class’ implementation, fwd declare it instead of including its header, because your header include guards will trip you up in confusing ways if you’re not careful.

Here’s a good article on tips for C++ includes:

1 Like

Thanks for the info. I was making a mistake and had everything in .h files. Just a side question: can I use using namespace xxx in .h files or should I rather use it in .cpp files as well?

I avoid using statements in my headers, either they go in my cpp file after all other headers or I use them locally in methods.

I’m a solo developer though, so even if I did have using statements littered around my headers it probably wouldn’t be a big deal. But if multiple people had to work with my source, or if I were distributing it, using statements in my headers could get really annoying.