So I'm trying to program a Conway's Game Of Life type game in one dimension. For the cell
class, I want to have two references that point to the cell to the right and the cell to the left.
However, I'm having trouble working out how to structure the code, and whether to use pointers or references, and what exactly &
and *
do in context.
The issues I'm running into are that I cant initialise a cell object without already having the right and left cells initialised, which isn't possible - I think this is circular dependency?
cell class
class cell {
private:
const Vector2 size = {100.0, 100.0};
Vector2 position;
cell &right;
cell &left;
public:
cell(Vector2 in_position);
std::vector<cell> get_pointers() {
return {*right, *left};
}
void set_pointers(cell &in_right, cell &in_left) {
right = in_right;
left = in_left;
}
};
cell::cell(Vector2 in_position) {
position = {in_position.x - size.x/2, in_position.y - size.y/2};
}
With this code I get warnings like
no operator "*" matches these operands
and
function "cell::operator=(const cell &)" (declared implicitly) cannot be referenced -- it is a deleted function`.
I've tried moving around the dereference operators but because I don't fully understand how to use them, I can't get it to work.
Could someone help? I'm very new to C++.
I think you are making confusion between pointers and references
While a pointer is an object itself which stores the adress of another object it is pointing to, a reference is not. Making a reference to an object is, simply put, like calling the object with another name.
Because of this:
A reference cannot be null: this implies that, the way you made it, any cell class needs to have necessarily one right cell and one left cell. If you use a pointer, on the other hand, so writing:
cell* right;
cell* left;
you could set either right or left to nullptr
in case the cell doesn't have a right cell or a left cell.
A reference cannot be reset: this implies that, when you create a cell class, there would need to be already two other cell classes ready (to initialize the referenes), and you would not be able to change the right or the left cell member for any cell class. This, on the other hand, is possible with pointers.
Also note that you cannot dereference references, like you did in
std::vector<cell> get_pointers() {
return {*right, *left};
}
the * dereference operator is used with pointers and returns the data the pointer is pointing to.
Also, you get the error
function "cell::operator=(const cell &)" (declared implicitly) cannot be referenced -- it is a deleted function`.
because you cannot write right = anything, because as I said references cannot be reset, you could do this if right was a pointer instead.