I store pointers to all instances of class Cell in a linked list. The std::list<Cell*> cells is stored in a class named Game. The method Game::update() iterates trought all instances of Cell held in the list cells, and calls each cell’s Cell::update() method. If the Cell::update() method finds out at some point that the cell is ready to divide, it needs to push_back() a pointer to the new cell to cells in order for the new cell to be updateable.
But how can I refer to Game::cells within the cell in order to do that? I have considered the following options:
- Defining
std::list<Cell*> cellsin global scope instead.- nasty and makes it impossible to have more than one
Game
- nasty and makes it impossible to have more than one
- Making
std::list<Cell*> cellsa static member ofCell- better than the global var but still prevents the use of multiple
Gameinstances
- better than the global var but still prevents the use of multiple
- Passing a reference to the current game’s
Game::cellsas a parameter to the Cell’s constructor and subsequently storing a copy of that reference in the newly constructed cell instance- I think it is a little inflexible
- Passing a reference to the current game’s
Game::cellsas a parameter to theCell::update()method
Are there more elegant solutions to utilize?
I would not introduce an unnecessary dependence between
CellandGame, if allGamedoes is to call methods onCells and hold instances of them.You could instead return new
Cells (or none) fromCell::update()and letGamedecide what to do, most probably add them to the list. You could also define a new function for this inCell, something likeCell::splitCell()and letCell::update()only update properties ofCellobjects (as the name would suggest).