Three classes Zoo, ZooObject and Animal are present.Is it valid to declare a 2D array of ZooObjects like mentioned below? If so, how do i initialise it? I am familiar with dynamically allocating a 2D array, but can't figure out this one.
class ZooObject;
class Zoo {
public:
int rows, cols;
ZooObject ***zooArray;
Zoo(int rows, int cols) {
this->rows = rows;
this->cols = cols;
// dynamically initialize ***zooArray as a 2D array with each
//element of type Animal
// initially initialized to NULL.
// initialize each row first.
for (i = 0; i < rows; i++) {
zooArray[i] = new ZooObject *[cols];
}
// initialize each column.
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
Animal animal;
zooArray[i][j] = &animal;
}
}
}
};
class ZooObject {
public:
bool isAlive;
};
class Animal : public ZooObject {
public:
bool isHerbivore;
};
int main() { Zoo *zoo = new Zoo(3, 3); }
As already was mentioned, here is nice post where the general answer to the question was detailing explained. How do I declare a 2d array in C++ using new?
In your case, if you want to store this as 2D array. You should allocate first all rows, where each row is a ZooObject**
, which is ZooObject
`s pointers array.
And after, for each of the row, you should allocate the array (columns) of ZooObject*
. You will have something like this:
Zoo(int rows, int cols) {
this->rows = rows;
this->cols = cols;
zooArray = new ZooObject**[rows];
for (int i = 0; i < rows; ++i) {
zooArray[i] = new ZooObject*[cols];
for (int j = 0; j < cols; ++j) {
zooArray[i][j] = nullptr;
}
}
}
However, consider using 1D arrays, you still can access it via 2 dimensions, via corresponding method, which converting rowId, colId
pair to 1D dimension.
Also, don't forget to delete
which you new
!