I’m partial to using member initializer lists for my constructors, but I’ve long since forgotten the reasons behind this.
Do you use member initializer lists in your constructors? If so, why? If not, why not?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
For trivial type data members, it makes no difference, it’s just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider:
In this case, the constructor for
Bwill call the default constructor forA, and then initializea.xto3. A better way would be forB‘s constructor to directly callA‘s constructor in the initializer list:This would only call
A‘sA(int)constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will thatA‘s default constructor did more, such as allocating memory or opening files. You wouldn’t want to do that unnecessarily.Furthermore, if a class doesn’t have a default constructor, or you have a
constor reference data member, you must use an initializer list: