Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of constructor in C++

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.

like image 651
Amar Avatar asked Jul 04 '11 18:07

Amar


People also ask

What is the used of constructor?

Constructors, which concretely use a single class to create objects and return a new instance of the class, are abstracted by factories, which also create objects but can do so in various ways, using multiple classes or different allocation schemes such as an object pool.

What is the use of constructor in real life?

Constructors are generally useful for writing user-specific values to the instance variables. These can also be used when the programmer needs to set explicit or default values to the member variables of the class.


2 Answers

Technically speaking, your interpretation is accurate. No members may be initialised from inside the ctor body; only in the ctor-initializer. Any member access in the ctor 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.

like image 131
Lightness Races in Orbit Avatar answered Sep 18 '22 18:09

Lightness Races in Orbit


You're overthinking it and allowing the interviewer to confuse you.

Initializing the members of an object is not the same thing as initializing the object itself. Just because the members have sane values doesn't mean the object has been constructed. Until the constructor has completed, the object itself has not been properly initialized.

like image 36
Nicol Bolas Avatar answered Sep 17 '22 18:09

Nicol Bolas