Allocation as default initialization
This code is not correct.
int* t = new int[l];
will happen before l=length;
, thus reading the uninitialized variable l
. Member initializers are handled before the constructor's body runs.
array::array(int length) : l{length} {}
instead would work because l
is declared before t
.
However, doing this "by hand" is a bad idea to begin with. You should be using std::vector
.
The 2nd code snippet might have undefined behavior.
The data members are initialized at the order of how they're declared. For class array
, when t
is initialized l
is not initialized yet. For objects with automatic and dynamic storage duration l
will be initialized to indeterminate value, then the usage of l
(i.e. new int[l]
) leads to UB.
Note that l=length;
inside the body of the constructor is just assignment; the initialization of data members has been finished before that.
BTW: With member initializer list the 1st code snippet chould be rewritten as
array::array(int length) : l(length), t(new int[l]) {
}