0

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;

sebXIII1
  • 29
  • 6

1 Answers1

1

Add forward references. BTW, there's no reason to use three header files. None of the classes is of any use without the others, so put them all into one header. And a namespace would be nice.

#ifndef SNAKEBODY_HPP_
#define SNAKEBODY_HPP_

class SnakeHead;  // Here
class SnakeGame;  // and here

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_ */
Jive Dadson
  • 16,680
  • 9
  • 52
  • 65