I am currently coding a Tile class to be used in my BFS algorithm. I need a cameFrom
variable that will keep track of where the tiles came from as I traverse a grid. It should not be initialized at the start as we do not know where it came from at the start. As I run through my BFS algorithm, it will continuously update.
Error 1 error C2758: 'Tile::cameFrom' : a member of reference type must be initialized
Anyone know what is wrong?
Here is my Tile.hpp:
#ifndef _TILE_H
#define _TILE_H
class Tile
{
public:
Tile(int x, int y);
~Tile();
int GetX();
int GetY();
bool IsWall();
bool IsVisited();
void SetCameFrom(Tile& cameFrom);
Tile& GetCameFrom();
void ToggleWall();
void ToggleVisited();
private:
int x;
int y;
bool isWall;
bool isVisited;
Tile& cameFrom;
};
#endif
My Tile.cpp:
#include "Tile.hpp"
Tile::Tile(int x, int y) {
this->x = x;
this->y = y;
this->isWall = false;
this->isVisited = false;
}
Tile::~Tile() {}
int Tile::GetX() {
return x;
}
int Tile::GetY() {
return y;
}
bool Tile::IsWall() {
return isWall;
}
bool Tile::IsVisited() {
return isVisited;
}
void Tile::SetCameFrom(Tile& cameFrom) {
this->cameFrom = cameFrom;
}
Tile& Tile::GetCameFrom() {
return cameFrom;
}
void Tile::ToggleWall() {
isWall = !isWall;
}
void Tile::ToggleVisited() {
isVisited = true;
}
Firstly reference must be initialized, so you would have to set it in the constructor. Secondly you can't re-assign reference, so your SetCameFrom
function won't work. Use pointers for this.
Tile * cameFrom;
But it's also good to initialize pointer to 0 (or nullptr in C++11) in the constructor.
Tile::Tile(int p_x, int p_y):
x(p_x),
y(p_y),
cameFrom(0),
isWall(false),
isVisited(false)
{
}