Take this program as an example:
class Piece
{
public:
Piece(bool color);
protected:
bool color;
};
Piece::Piece(bool color)
{
this->color = color;
}
//-----------------------------
class King : public Piece
{
public:
King(bool color);
};
King::King(bool color) : Piece(color)
{
// empty
}
//-----------------------------
class Tile
{
public:
// constructors/destructors
Tile(Piece * ppiece, int rrow, int ccol);
~Tile();
private:
Piece * piece;
int row, col;
};
Tile::Tile(Piece * ppiece, int rrow, int ccol)
{
this->ppiece = piece;
this->row = rrow;
this->col = ccol;
}
//---------------------------
int main()
{
Tile * tile = new Tile(new King(0), 1, 1);
}
In the function main() I declare a new King and pass it to the Tile constructor. How can I delete the King object I created?
As written, the Tile Constructor receives the new King as parameter
ppiece.The Tile Constructor then doesn’t do anything with ppiece, and the memory is cannot be freed. It is “leaked”.
Given that Tile has a member
piece, I’d suggest assigning it there:Then you can later free it in the Tile destructor: