0
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ 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.) \$\endgroup\$
    – Komi Golov
    Jul 5, 2012 at 23:03
  • \$\begingroup\$ 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. \$\endgroup\$ Jul 6, 2012 at 16:55

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the quick reply, I seem to have gotten things working. \$\endgroup\$ Jul 5, 2012 at 20:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .