Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ With Initializer List a thing, when to use normal constructor?

Tags:

c++

I just started getting back into C++ here recently and learned about Initializer Lists. It seems to be the standard way to initialize members. That being said I have 2 questions regarding it:

  1. Is there ever a reason to NOT use this method when setting private member variables (and just using the old fashioned setting it in the constructor).

  2. What exact benefit do we get from this? I've been told "speed" but not exactly why?

edit: For reference Im more specifically speaking of using them for class initialization.

like image 854
msmith1114 Avatar asked Nov 30 '22 21:11

msmith1114


2 Answers

Initialization list is about calling ctor of member variables. If you assign, you are altering the value of instance by using assign function. Obviously, these two are different functions.

There are a few cases that you cannot assign value to member variable in the ctor.

  • When the member variable is const.
  • When the member variable is an instance of class without default ctor.
  • When the member variable is a reference (same reason as above)
  • Initializing base class

When you create an instance without init-list, the member variable runs its ctor and then assign if you give value to it. It's a subtle difference but it might incur some penalty as the ctor runs first, and assign runs 2nd - which is unnecessary overhead.

like image 155
Naoyuki Tai Avatar answered Dec 15 '22 04:12

Naoyuki Tai


You should know that "setting (member data) in the constructor (body)" is assignment to an already-initialized object. That cannot supply constructor arguments. const members and references cannot be assigned.

The ctor-initializer-list (and since C++11, brace-or-equal-initializers specified at the member point of declaration) do true initialization, and should be preferred.

The constructor body can still have some uses... doing things with side effects, or looping... but even these can be accomplished by invoking a helper function from inside one of the ctor-initializer-list expressions.

Also, member initialization is the only way for their setup to fail in a way that doesn't lead to later destruction. An exception in a constructor body will abort creation of the parent object... but destructors still need to run for all subobjects, so any setup to put them in a known, destructable state has to already be complete.

like image 40
Ben Voigt Avatar answered Dec 15 '22 04:12

Ben Voigt