In your trivial case, it doesn't matter.
In general, you can initialize instance variables in a few ways:
Inline
class Example1 {
T x = value;
}
Advantages:
- Direct, concise.
- Member will be initialized in all constructors.
- Can be used to initialize
final members.
- Member is initialized before invoking base class constructors, which can matter if the base class constructor calls member functions that are overridden by the derived class.
Disadvantages:
- Can't depend on construction arguments.
- Can't depend on
this since the initialization occurs before this becomes valid.
Initialization list
class Example2 {
T x;
Example2() : x = value;
}
Advantages:
- Can be used to initialize
final members.
- Member is initialized before invoking base class constructors, which can matter if the base class constructor calls member functions that are overridden by the derived class.
- Can utilize construction arguments.
Disadvantages:
- If the class has multiple constructors, initialization would need to be duplicated, or constructors should redirect to a common constructor.
- Can't depend on
this since the initialization occurs before this becomes valid.
Constructor body
class Example3 {
T x;
Example3() {
x = value;
}
}
Advantages:
- Can utilize construction arguments.
- Can be used to perform more complicated initialization, such as cases where the member cannot be initialized via a single expression.
- Can use
this.
Disadvantages:
- Cannot be used to initialize
final members.
- If the class has multiple constructors, initialization would need to be duplicated or initialization code would need to be refactored out (such as, but not limited to, redirecting to a common constructor).
- Member is initialized after invoking base class constructors.
There probably are some points I'm forgetting, but I think that should cover the main ones.
Direct, inline initialization occurs first, then initialization lists, then constructor bodies. Also see Difference between assigning the values in parameter list and initialiser list which explains why this becomes valid only for the later stages of object initialization.