This is very trivial question regarding the use of a constructor in C++. I will present in the form of an interview dialogue (it was difficult to present it in any other forms)
interviewer – what is a constructor?
me – constructor are special functions which makes sure that all objects are initialized before their use.
interviewer – what is an initializer list?
me – that is a list where all the initialization happens. A constructor's body is entered only after all the data members are initialized, or some constructor of all the member objects are called.
interviewer – that means initialization is carried out in initializer list, not inside constructor. But you said constructor initialize the object! Didn't you? Do you want to answer my first question.
me – I think constructor does assignment, it calls assignment operator on already initialized member objects.
So my question to you can be
how initializer list works?
what lies between function's starting address & starting braces [{]?
or just answer me how to convince my interviewer.
Best Answer
Technically speaking, your interpretation is accurate. No members may be initialised from inside the
ctor
body; only in thector-initializer
. Any member access in thector
body may only be assignment.All members are "initialised" before the
ctor
body is entered.However, speaking more broadly, since the body always follows the initializer, it's said that — as a unit — the object is initialised once the constructor has ended... including the body.
Partly this is because, again speaking broadly, you might consider initialisation to include some business logic that you must perform in your
ctor
body, even though this is not the same as actual initialisation of a data member.