Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ circular include

I can't solve this circular dependency problem; always getting this error: "invalid use of incomplete type struct GemsGame" I don't know why the compiler doesn't know the declaration of GemsGame even if I included gemsgame.h Both classes depend on each other (GemsGame store a vector of GemElements, and GemElements need to access this same vector)

Here is partial code of GEMELEMENT.H:

#ifndef GEMELEMENT_H_INCLUDED
#define GEMELEMENT_H_INCLUDED

#include "GemsGame.h"

class GemsGame;

class GemElement {
    private:
        GemsGame* _gemsGame;

    public:
        GemElement{
            _gemsGame = application.getCurrentGame();
            _gemsGame->getGemsVector();
        }
};


#endif // GEMELEMENT_H_INCLUDED

...and of GEMSGAME.H:

#ifndef GEMSGAME_H_INCLUDED
#define GEMSGAME_H_INCLUDED

#include "GemElement.h"

class GemsGame {
    private:
        vector< vector<GemElement*> > _gemsVector;

    public:
        GemsGame() {
            ...
        }

        vector< vector<GemElement*> > getGemsVector() {
            return _gemsVector;
        }
}

#endif // GEMSGAME_H_INCLUDED
like image 383
Nikola C Avatar asked Jul 25 '13 17:07

Nikola C


1 Answers

Remove the #include directives, you already have the classes forward declared.

If your class A needs, in its definition, to know something about the particulars of class B, then you need to include class B's header. If class A only needs to know that class B exists, such as when class A only holds a pointer to class B instances, then it's enough to forward-declare, and in that case an #include is not needed.

like image 139
DUman Avatar answered Oct 28 '22 14:10

DUman