I do see a couple of problems.
In the fill() function every pointer in the 2d array has an Animal allocated to it (line 25).
On line 31, a number of these animals are placed via call to placeAnimal().
Line 46: arr[i][j] is overwritten with a new Animal*, and the Animal allocated to arr[i][j] in fill() is lost.
The previously allocated Animal should be deleted first:
1 2
|
delete arr[x][y];// destroy existing
arr[x][y] = new Animal;// create new
|
Why destroy and allocate new? There is no change in types pointed to. Animal before and after. Why not just call
arr[x][y]->setAnimal(x, y);
on the existing instance?
destroy and renew is useful when changing polymorphic types, like if Dog and Cat are derived from Animal:
1 2 3 4 5
|
Animal* pA = new Cat;// pA points to a Cat
pA->speak();// output = meow
delete pA;// destroy the cat
pA = new Dog;// now pointing to a Dog
pA->speak();// output = woof
|
Another problem is in ~Board(). No Animals are deleted, only the pointers!
Reverse the construction.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
// construction
arr = new Animal**[rows];
for (int i = 0; i < rows; i++)
{
arr[i] = new Animal*[cols];
for (int x = 0; x < cols; x++)
{
arr[i][x] = new Animal;
}
}
// destruction
Board::~Board()
{
for (int i = 0; i < numRows; i++)
{
for (int x = 0; x < numCols; x++)
{
delete arr[i][x];// each Animal
}
delete [] arr[i];
}
delete [] arr;
}
|
Lastly, why pass rows, cols to the fill() function? Every array element is to be allocated to, so must have rows = numRows and cols = numCols.
ie.
1 2 3 4 5
|
void Board::fill(int animals)
{
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
|