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:
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).
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.
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 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With