I wanna create a field for a little game. The field consists of the followed classes:
Floor
Wall
Door
All 3 of them are derived classes of the abstract class Tile. With it I wanna create the field with 7x7 per Polymorphism. The field should be on the heap so it cannot be vanished by the compiler.
Good point, I should have made an array of pointers.
Well:
Tile* is Tile pointer or array of Tile.
Tile** is array of Tile pointer
Tile*** is array of array of Tile*
So we are dealing with arrays of arrays. So you need to allocate an array and then visit each element of that array to allocate another array to each one:
const size_t x_size = 7;
const size_t y_size = 7;
// Declare an 'Tile***' (array of array of Tile*)
Tile*** field;
// Allocate your 'Tile***'
field = new Tile**[x_size];
// Every element is a 'Tile**' (array of Tile*)
// Visit every 'Tile**' element
for(size_t x(0); x < x_size; ++x)
{
// Allocate a 'Tile*' to each 'Tile**' element
field[x] = new Tile*[y_size];
// Every element of this array is a 'Tile*' (array of Tile)
// Visit every 'Tile*' element
for(size_t y(0); y < y_size; ++y)
{
// Allocate a Tile to every Tile* element
field[x][y] = new Tile;
}
}
Before you know it you'll be knowing nested #if #elsif macros and no one but you will be able to maintain your code :P.
May I suggest wrapping your "Field" in a class as well, and only using an array of Tile* of size m * n, and accessing your array elements using an overload operator(). It will make things MUCH MUCH easier in the long run, there are also less pointer chases so it is more efficient.