Constructor With Array

Started by
5 comments, last by j0mich01 17 years, 6 months ago
I'm trying to allocate space for an array of a class that accept two arguments (x and y) in its constructor. This is my code, for some reason i keep getting an error. If I just remove the array part it compiles just fine.


Gameboard* m_Board = new Gameboard(x,y)[100];



Advertisement
You can't do that!

Try

Gameboard* m_Board[100]; // ( for stack variable)
Gameboard** m_Board = new Gameboard*[100]; // ( for heap variable)

for (int i = 0; i < 100; ++i)
{
m_Board = new Gameboard(x,y);
}
You need to have a default (i.e. no argument or all default arguments) contructor if you use operator new[] for an array of elements.

Don't ask me why...
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
Quote:Original post by j0mich01
I'm trying to allocate space for an array of a class that accept two arguments (x and y) in its constructor.


Array elements can only be default-constructed.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Thanks for all the help.. Incin's way worked the problem out.
Of course, if you were to use the standard library you could get the behaviour you desire without incurring loss of locality-of-reference and significant additional memory management issues:

std::vector< Gameboard > m_board(100, Gameboard(x, y));

constructs a vector containing 100 copies of the gives Gameboard.

Σnigma
Funny thing is, after looking at my code closer, I didn't even need to do this, I don't need multiple gameboards! lol, I need multiple tiles within the gameboard. The gameboard constructor need the x and y values and then I just create the array of Tiles within the gameboard constructor.

This topic is closed to new replies.

Advertisement