An initializer list is required to initialize some variable types, e.g. references. Here is an example of how a reference type works:
Code:
#include<iostream>
using namespace std;
int main()
{
int num1 = 10;
int num2 = 35;
int& rInt = num1; //declare a reference variable and initialize it to num1
rInt += 10;
cout<<num1<<endl; //20 (rInt is like a nickname for num1, so changing
//rInt changes num1.)
rInt = num2; //try to switch the reference to another variable
rInt += 4; //did rInt change num2?
cout<<num2<<endl; //35(Nope!)
cout<<num1<<endl; //39 ??? (rInt is a synonym for num1, so rInt = num2 assigned
//num2 to num1, and rInt += 4 added 4 to num1.)
return 0;
}
The result of all that is that you can't change what a reference refers to. rInt refers to num1 and that is all it will ever refer to, and doing something to rInt is the same as doing it to num1 directly. In order to set which variable a reference refers to, you have to initialize the reference variable when you declare it:
If you don't initialize a reference variable when you declare it, the reference variable won't be able to refer to anything. Here is an example of that:
Code:
int age = 23;
int& rAge;
rAge = age; //error
That is relevant to constructors and initializer lists because a constructor first constructs the object before it gets to the opening brace of the constructor body. Therefore, all the member variables have been created by that point, and a member variable that is a reference type will be created so that it doesn't refer to anything. That means in the constructor body it's too late to try and assign a variable name to the reference. On the other hand, using an initializer list causes the listed variables to be initialized with the specified values as they are created.