0

For the below code snippet, how do I initialize instances of class Enemy with variables (such as x, y, type)? I have it working correctly, it triggers the instances no matter how many of them I insert... I just need to know the best way of creating an enemy with certain variables that will differ for each of my instances... particularly when some of those variables are in the base class and others are not.

class BaseObject
{
public:
    virtual void Render() = 0;
    int x;
    int y;
};

class Enemy : public BaseObject
{
public:

    Enemy() { }
    virtual void Render()
    {
        cout << "Render! Enemy" << endl;
    }

typedef std::set<BaseObject *> GAMEOBJECTS;
GAMEOBJECTS g_gameObjects;

int main()
{
    g_gameObjects.insert(new Enemy());

    g_lootObjects.insert(new Loot());

    for(GAMEOBJECTS::iterator it = g_gameObjects.begin();
    it != g_gameObjects.end();
    it++)
    {
        (*it)->Render();
    }

    for(GAMEOBJECTS::iterator it = g_lootObjects.begin();
        it != g_lootObjects.end();
        it++)
    {
        (*it)->Render();
    }

    return 0;
}

1 Answers1

4

Include the arguments in the enemy constructor and Base constructors. You can then use those to initialize the member variables.

class BaseObject
{
public:
    BaseObject(int x, int y) : x(x), y(y){ }
    virtual void Render() = 0;
    int x;
    int y;
};

and

class Enemy : public BaseObject
{
public:

    Enemy(int x, int y, int foo) : BaseObject(x,y), foo(foo) { }

    int foo;
...
};
GWW
  • 43,129
  • 11
  • 115
  • 108
  • Thanks! That works perfectly. What an odd syntax... Would you mind clarifying for me why one types the : x(x), y(y){} part? What does the first and second x in x(x) correspond with, and what purpose do the empty squigglies serve? – motioneffector Mar 16 '11 at 18:39
  • @motioneffector: It may seem odd at first but you'll grow to like it. It's really quite nice compared to some other languages. – GWW Mar 16 '11 at 18:40
  • 1
    The parenthesis signify calling the constructor of the objects the _squigglies_ are the body of the function in this case an empty constructor for your classes. This is known as an initializer list and is the faster more efficient equivalent of doing assignments in your constructor for member variable initialization. – AJG85 Mar 17 '11 at 22:01