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 quest
The constructor initializer list is a very useful tool. I would reject your code in code review if you wouldn't be using it.
C++ has 2 ways of initializing members. Whenever you declare your member, you can give it a default value:
class C {
int i = 42;
public:
C(int j);
C() = default;
};
This is a very useful technique to initialize simple members on a good default value.
Than, you have the initializer list:
C(int j) : i{j} {}
In this list, you can override the initialization. All members not mentioned get the initialization from the definition. Note that classes with default constructors don't require explicit initialization.
The initializer list can use the arguments of the constructor. However by initializing the members on definition, it is easier to spot uninitialized members.
So when not to use the initializer list for initialization? Never, as assignment in the constructor body is assignment, not initialization.
You never really need the body to assign members, however, if you don't have the -Wreorder
warning active, it might make sense to assign a member that depends on another.
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.
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.