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)
{
}
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.
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:
const
but not static must be initialized using an initialization list.employee
constructor example above).