How does a constructor create and initialize member variables?

Viewed 120

Consider the following class with member initializer list:

class A {
public:
    A() : a {b} {
       // do something
    }
private:
    int a {1};
    int b {2};
};

The compiler issues a warning that b is used uninitialized in the member initalizer list. This would mean, the member b has been already created but not initialized yet?

Thus, can we assume the following order of execution?

  1. call constructor A()
  2. int a; (create memory for a)
  3. int b; (create memory for b)
  4. a = b; (compiler warning)
  5. b = 2; (assign default 2 to b)
  6. execute constructor's block

This would mean, we actually do not initialize but assign values in step 4 and 5?

EDIT: If so, what is the advantage of an initializer list, when assignments can also be done in the block after the members have been created prior entering the block?

1 Answers

The sequence you describe is not completely correct. The sequence goes basically as follows:

  1. The memory for the object is allocated; (e.g. using operator new) Note that the memory is not allocated separately. The memory for the object is continuous, possibly with padding in between a and b.
  2. Initializations of members are done where initializers are provided in the initializer list of the constructor or directly at the member declaration. in this case a is declared first then b which is why b has not been initialized at the time you try to read it to initialize a.
  3. The constructor body is executed.

Note that the fields are initialized, not assigned which in case of ints doesn't make a difference, but if the member types would provide assignment operators and constructors there would be a difference between the 2; if you use the initializer list or initialize the member variable when declaring it the constructor is always used.

Related