i'm working on a Snake game and i'm having trouble with Circular Reference in C++. This is the header of the class SnakeBody who represent anypart of the Snake that is not the head.
#ifndef SNAKEBODY_HPP_
#define SNAKEBODY_HPP_
class SnakeBody {
public:
SnakeBody(SnakeHead *origin, int left, int x, int y);
~SnakeBody() = default;
void move();
void grow(int size);
protected:
SnakeBody *next;
SnakeHead *head;
SnakeGame *game;
int x;
int y;
int growWait;
};
#endif /* !SNAKEBODY_HPP_ */
And there is the source code (the part containing the constructor).
#include "../include/SnakeHead.hpp"
#include "../include/SnakeGame.hpp"
#include "../include/SnakeBody.hpp"
SnakeBody::SnakeBody(SnakeHead *origin, int left, int x, int y)
{
this->head = origin;
this->game = this->head->getGame();
this->x = x;
this->y = y;
this->growWait = 0;
if (left > 0)
this->next = new SnakeBody(origin, left - 1, x + 1, y);
else
this->next = nullptr;
}
I have been carefull about make every include in source and not header to avoid unfinished reference and loop. But it still appear that SnakeHead has a undefined reference.
SnakeBody : Any part of the snake that is not the head. SnakeHead : The head of the snake. SnakeGame : Contain the state of the board, need a reference of SnakeHead and SnakeHead and SnakeBody need a reference of SnakeGame to get data about the state of the game (ie : wall, food, etc...).
The error message is : ./src/../include/SnakeBody.hpp:19:9: error: ‘SnakeHead’ does not name a type; did you mean ‘SnakeBody’? SnakeHead *head;