I want to create a class which has several pointers to other instances of this class. I want to create game of life where I can set the neighbour cells.
The problem that I have is that I can’t assign a reference to my const pointer member variables.
class Cell {
...
const Cell* left;
...
void setLeft(const Cell & left) {
this->left = left;
}
}
I had the idea to save all cells in a vector something like this
std::vector<Cell::Cell> cells;
and then access and set them like this cells[pos].setLeft(cells[left]);(pos and left would be integers)
I get the following error msg. Can't convert const cell to const cell* in assignment.
Also it can’t find the method setLeft
I come from a java/net background so maybe I just made a huge mistake.
You’re mixing up pointers and references (which is understandable when you’re comming from java/net). In C++, there is a clear distinction between:
Cell x;, an object (instance) of classCellCell *x;, a pointer to an instance ofCellCell &x;, a reference (“another name”) to an instance ofCellJava “references” are equivalent to C++ pointers.
In your case, there are several issues. First,
setLeft()needs to get the address of its argument, like this:Second, unless the class
Cellis defined in a namespaceCell, the vector would have to be typed juststd::vector<Cell> cells;.However, even more dangerous is the fact that your vector contains statically allocated
Cellobjects (its template argument is a class type, not a pointer).std::vectoris allowed to move objects around in memory when it’s added to, so once this happens, all existing pointers to objects stored incellswill become dangling. What you should do is store pointers in the vector instead:It might actually be even better to use smart pointers (
std::shared_ptrandstd::weak_ptr) instead of raw pointers, but that’s a separate topic.