Search code examples
c++oopcircular-dependencyforward-declaration

Invalid use of incomplete type circular dependency c++


I have 2 classes with circular dependency:

GameState.h

#include "Ball.h"

class GameState{
    Ball ball;
public:
    //...
    void groundTouched();
};

Ball.h

#include "GameState.h"

class Ball{
public:
    //...
    void update(GameState* gameState);
};

Ball.cpp

#include "Ball.h"

void Ball::update(GameState* gameState){
    gameState->groundTouched();
}

and of course i have error like:

Ball.h:34:69: error: ‘GameState’ has not been declared

then i used forward declaration there:

class GameState;
class Ball{
public:
    //...
    void update(GameState* gameState);
};

but then there is an error:

Ball.cpp:51:22: error: invalid use of incomplete type ‘class GameState’

How can i call GameState method from a Ball? Is it possible? I know i can remove GameState.h from Ball and do something like ball.isGroundTouched() from GameState but for me first option looks more object oriented and preferred.


Solution

  • You must still include the GameState.h header file in the source file Ball.cpp.