Sign in to follow this  

Constructor With Array

This topic is 4070 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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];



Share this post


Link to post
Share on other sites
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[i] = new Gameboard(x,y);
}

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4070 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this