Initializers for Instances
Let's understand the purpose of initializers in constructors.
We'll cover the following
Member initializer lists #
An initializer list is used to initialize the members in the constructor of a class. The list is added before the body of the constructor.
Rather than creating the variables and then assigning values to them within the constructor’s body, an initializer list initializes the variables with their particular values. The list also makes the constructor’s implementation simpler and more readable.
One may wonder why this is useful. Well, consider that our class has a const
attribute. Naturally, it would have to be initialized. Assigning it values in the constructor’s body will cause an error.
This is where an initializer would solve the problem.
The list is appended after the parameters of the constructor and a :
.
class Account{
public:
Account (double b): balance(b), minBalance(25.0){}
private:
double balance;
const double minBalance; ....
};
Rules #
-
As discussed, non-static attributes that are declared
const
or as a reference must be initialized in the initializer list. -
The sequence of initialization corresponds to the sequence in which the attributes were declared.
-
static
attributes cannot be initialized in the initializer of the constructor.
Example #
Get hands-on with 1400+ tech skills courses.