Constructor Initialization Lists


Initialization lists are an alternative technique for initializing an object's data members in a constructor. For instance, the constructor

date::date(int m, int d, int y)
{
    month = m;
    day = d;
    year = y;
}

can instead be written using an initialization list:

date::date(int m, int d, int y) : month(m), day(d), year(y)
{
}

Both built-in types and objects can be initialized using initialization lists. Arrays (including C strings) can not be initialized using initialization lists.

Initializing an object this way results in a constructor call. For example, if a class called employee has a date object called hire_date as one of its data members, we could use an initializer list to initialize the hire_date data member in the employee constructor:

employee::employee(const string& name, int hire_month, int hire_day, int hire_year) :
                   employee_name(name), hire_date(hire_month, hire_day, hire_year)
{
}

Initialization Lists and Scope Issues

If you have a data member of your class that has the same name as a parameter to your constructor, then the initialization list "does the right thing." For instance,

date::date(int month, int day, int year) : month(month), day(day), year(year)
{
}

is roughly equivalent to

date::date(int month, int day, int year)
{
    this->month = month;
    this->day = day;
    this->year = year;
}

That is, the compiler knows which month belongs to the object, and which month is the local variable that is declared in the member function.

When to Use Initializer Lists

Using initialization lists to initialize data members in a constructor can be convenient if you don't need to do any error-checking on the constructor arguments. There are also several instances in C++ where the use of an initializer list to initialize a data member is actually required:

  1. Data members that are const but not static must be initialized using an initialization list.
  2. Data members that are references must be initialized using an initialization list.
  3. An initialization list can be used to explicitly call a constructor that takes arguments for a data member that is an object of another class (see the employee constructor example above).
  4. In a derived class constructor, an initialization list can be used to explicitly call a base class constructor that takes arguments.