Is it good/bad practice to initialize your vars in your protoypes???

So I've been taught (from "C++ Programming/ From Program Analysis to Design" book) to initialize my private variables in the constructor in the definition of a class but......I just played around and initialized a variable inside my class prototypes and it worked. Is it bad to do so or does it matter?
Can you post an example of what you did?

You can only specify default parameters in a prototype, that's not quite the same thing as initialising members.
Sure. This is the class prototype and it compiles just fine.
Line 16 is where I actually initialize a var.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class enemy
{
public:
    enemy();
    void attackThePlayer(player& player);
    void run(int, int);//take into account health and players level and such
    void returnEnemyStats();//health, attack power and such;
private:
    int health;
    int defense;
    int attackPower;
    int bossesKilledCounter;
    int enemiesKilledCounter;
    bool isEnemyDead;
    string getRandomEnemy;
    vector<string> enemyList {"Scorpion", "Bug", "Hyena", "Wolf",
                "Cat", "Shadow", "Dr. Fetus",
                "Dark Link", "Majin Boo", "Dr. Mario",
                "Dr. Mr. Evil"};
};



This is how I've been taught to initialize vars....inside your
class constructor:

1
2
3
4
5
6
7
8
enemy::enemy()
{
    //11 different enemies as of now
    enemyList = {"Scorpion", "Bug", "Hyena", "Wolf",
                "Cat", "Shadow", "Dr. Fetus",
                "Dark Link", "Majin Boo", "Dr. Mario",
                "Dr. Mr. Evil"};
}


Both ways work just fine. Just wondering why have a constructor when
vars can be initialized inside a class prototype. Thanks.


EDIT - What's the difference between specifying a default param and initializing a member?
Last edited on
Topic archived. No new replies allowed.