I think only the following headers are relevant here:
Game.h
#include "Player.h"
class Game
{
private:
Player White;
Player Black;
Board current_board;
};
Player.h:
#include "Game.h"
#include "Piece.h"
class Player
{
private:
Chessend end;
std::string name;
std::vector <Piece> pieces;
Board* board_ptr;
Game* game_ptr;
};
Piece.h:
#include "Player.h"
class Player; //forward declaration
class Piece
{
private:
Chesspiece type;
bool moved, taken;
Player *player;
};
gives the following error
In file included from Player.h:11:0,
from Game.h:1,
from main.cpp:1:
Game.h:20:10: error: field 'White' has incomplete type 'Player'
Player White;
^
In file included from Player.h:9:0,
from Game.h:1,
from main.cpp:1:
Piece.h:7:7: note: forward declaration of 'class Player'
class Player;
I know there is a forward declaration in Piece.h but I'm not sure why this is a problem.
1) Add guards against double-inclusion in all your header files. Easiest way (supported by most compilers):
#pragma once
2) To break the circular dependency, in Player.h dont #include Game.h, but only do a "forward-declaration" of the Game class, since you only need to use it via pointers:
class Game;
3) Similarly, in Piece.h dont #include Player.h, but only forward-declare the class Player:
class Player;
As an easy and general rule, when you see in a header file that you reference another class but only via pointer, don't include the header of this other class, but only forward-declare it. Not only will this rule break circular dependencies, but it will even minimize the dependencies, which results in faster compilation and better maintainability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With