Should I initialize my data in the class definition or in the constructor.

Certain pieces of data will always be initialized to the same value, regardless of the constructor called.

1
2
3
4
5
6
7
8
  Sailor::Sailor() {
        this->health = 25;
        // Some stuff here
  }
  Sailor::Sailor(int id, Location loc) {
        this->health = 25;
        // Some stuff here
  }


Otherwise, I could save some code by putting it in the class definition

1
2
3
4
5
6
7
8
9
class Sailor {
public: 
    Sailor();
    Sailor(int id, Location loc);    
    // stuff
private:
    int health = 25;
    // stuff
}


I want to pick the second choice, but my intuition tells me it's probably not the best practice. Are there any objections to initializing values inside the class definition?
Last edited on
I'm pretty sure you can't use the second choice. You would have to make health static and set it in the cpp file.

I always write an Init() function that all of my constructors call. If you end up having more than one constructor, it will save you a ton of work later!
With a compiler using the current standard the second snippet is okay.

In the first snippet you really should consider using the constructor initialization lists to initialize all your variables (in the order declared in the class):

1
2
3
4
Sailor::Sailor() : health(25), otherMemberVariables() {
// Try to keep this as empty as possible.
        // Some stuff here
  }


The initialization lists and your second snippet avoid unnecessary coping of data that happens if you initialize in the constructor body.

I always write an Init() function that all of my constructors call.

It may save you a few minutes when you write the class, but it will likely cause your program to take longer to initialize the variables every time you run the program. So if you just intend to run the program a couple of times it the savings in time probably won't be important. However if your class is called often the extra time taken can be significant.
Last edited on
@jlb: Agreed.
[quote]I always write an Init() function that all of my constructors call./quote]
Not to derail the thread, but is there something wrong with copy+paste in your environment?
Topic archived. No new replies allowed.