Execution of constructor is done in two phases:
The initialization phase
Body execution phase which consists of all the statements within the body of constructor. Note that data members of class type are always initialized in the initialization phase, regardless of whether the member is initialized explicitly in the constructor initializer list. Initialization happens before any the statement execution of the constructor body.
Let us consider a way of initializing an instance of class student by the constructor -
Student(string &fn, string &ln, int i, int y = Freshman)
: first_name(fn)
, last_name(ln)
, id(i)
, year(y)
{}
This is another , but 'inefficient' and 'inelegant' way of doing the same -
Student(string &fn, string &ln, int i, int y = Freshman)
{
first_name = fn;
last_name = ln;
id = i;
year = y;
}
This constructor in the new code (above code) assigns the members of class Student. It does not explicitly initialize them. Whether there is an explicit initializer or not, the first_name and last_name members are initialized even before the constructor is executed. This constructor implicitly uses the default string constructor to initialize the first_name and last_name members. When the body of the constructor is executed, the first_name and last_name members already have values. Those values are overwritten by the assignment inside the constructor body.
So ,this means by the time the execution reaches the opening bracket of the constructor , this is the condition -
- 'first_name', which is a string is initialized by calling the default string constructor ( the one which compiler 'makes') .
- 'last_name', which is a string is initialized by calling the default string constructor ( the one which compiler 'makes') .
- 'id', which is an integer is uninitialized .
- 'year', which is an integer is uninitialized .
And now ,it's clear , the assignments are done to each of the four variables , in the body of the constructor .
Is my understanding of this thing right ? I somehow feel I am missing something .
Also , while using the initialization lists , are the default constructors (one which compiler makes for us) , called and passed with our parameters (in case of string) and initialization done as in " int id = i ; " in case of id(i) ??
PS : Most of the quotes are from this link -