Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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.

share|improve this question
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
up vote 1 down vote accepted

There are a couple of problems here.

Firstly, enemyWave is a local variable and gets destroyed at the end of the constructor when it goes out of scope, which makes it useless as a long term data structure.

Secondly, everything you store in a vector needs to follow the rule of three. It's not clear if your Enemy classes do.

Apart from that, this is pretty much how you initialise a vector, an element at a time.

share|improve this answer
Thanks for the quick reply, I seem to have gotten things working. – Jackson Blades Jul 5 '12 at 20:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.