# C++ and SDL Trouble Creating a STL Vector of a Game Object

I am trying to create a Space Invaders clone using C++ and SDL. The problem I am having is in trying to create Waves of Enemies. I am trying to model this by making my Waves a vector of 8 Enemy objects.

My Enemy constructor takes two arguments, an x and y offset. My Wave constructor also takes two arguments, an x and y offset. What I am trying to do is have my Wave constructor initialize a vector of Enemies, and have each enemy given a different x offset so that they are spaced out appropriately.

Enemy::Enemy(int x, int y)
{
box.x = x;
box.y = y;
box.w = ENEMY_WIDTH;
box.h = ENEMY_HEIGHT;

xVel = ENEMY_WIDTH / 2;
}

Wave::Wave(int x, int y)
{
box.x = x;
box.y = y;
box.w = WAVE_WIDTH;
box.y = WAVE_HEIGHT;

xVel = (-1)*ENEMY_WIDTH;
yVel = 0;

std::vector<Enemy> enemyWave;
for (int i = 0; i < enemyWave.size(); i++)
{
Enemy temp(box.x + ((ENEMY_WIDTH + 16) * i), box.y);
enemyWave.push_back(temp);
}
}


I guess what I am asking is if there is a cleaner, more elegant way to do this sort of initialization with vectors, or if this is right at all. Any help is greatly appreciated.

• You've got a typo on the fourth line of Wave::Wave, I'm fairly sure it should be box.h. If you're using C++11, you may also want to use emplace_back instead of push_back. (These are not the most significant issues, see answers for those.) – Anton Golov Jul 5 '12 at 23:03
• As long as you dont store pointers or references to an Enemy object in the array, you are fine. However to prevent such subtile but hard to find errors, its best not to store objects, but pointers to objects in the array. – Maik Semder Jul 6 '12 at 16:55