The initializer list is used to directly initialize data members of a class. An initializer list starts after the constructor name and its parameters. The list begins with a colon ( : ) and is followed by the list of variables that are to be initialized – all of the variables are separated by a comma with their values in curly brackets.
Constructorname(datatype value1, datatype value2):datamember(value1),datamember(value2)
{
...
}
Using an initialization list is almost identical to doing direct initialization (or uniform initialization in C++11).
The following example uses an initializer list in the default constructor to set the value for the variable value
of the class.
#include<iostream>using namespace std;class Base{private:int value;public:// default constructorBase(int v):value(v){cout << "Value is " << value;}};int main(){Base myobject(10);return 0;}
There are several cases where the use of an initializer list is absolutely necessary, these include:
An initialization list is used to initialize a data member of reference type. Reference types can only be initialized once.
#include<iostream>using namespace std;class Base{private:int &ref;public:Base(int &passed):ref(passed){cout << "Value is " << ref;}};int main(){int ref=10;Base myobject(ref);return 0;}
const
data memberconst
data members can be initialized only once, so they must be initialized in the initialization list.
#include<iostream>using namespace std;class Base{private:const int var;public:Base(int constant_value):var(constant_value){cout << "Value is " << var;}};int main(){Base myobject(10);}
If you have a field that has no default constructor (or a parent class with no default constructor), then you must specify which constructor you wish to use.
#include<iostream>using namespace std;class Base_{public:Base_(int x){cout << "Base Class Constructor. Value is: " << x << endl;}};class InitilizerList_:public Base_{public:// default constructor using initializer listInitilizerList_():Base_(10){cout << "InitilizerList_'s Constructor" << endl;}};int main(){InitilizerList_ mylist;return 0;}