I am doing a chess project with cpp.
My board is a metrix of pointer to Piece, and when I construct it I allocate memory to different type of pieces ( Rook, King, Bishop ...).
(for example: this->_board[i][j] = new King()
)
I want to deep copy the board. My Idea is to itterate through the board, and for every piece I will allocate new memory to the type of the piece. What I tried:
for (int i = 0; i < NUM_ROWS; i )
{
for (int j = 0; j < NUM_COLUMN; j )
{
if (this->_board[i][j] != nullptr)
{
this->_board[i][j] = new typeid(*(other->_board[i][j]));
}
}
}
What command can I use instead of typeid(*(other->_board[i][j]))
, that will return a (King) type (for example), and I will be able to allocate memory for it?
thank you.
CodePudding user response:
You can use virtual function. For example,
class Piece
{
public:
virtual Piece* clone() = 0;
};
class King : public Piece
{
public:
virtual Piece* clone()
{
return new King(*this);
}
};
and then deep copy with other->_board[i][j]->clone()
.