Home > Mobile >  What is the actual mechanism behind the constructor initializer list?
What is the actual mechanism behind the constructor initializer list?

Time:06-21

There are cases where we must use an initializer list in order to initialize members, like when we have const data members. So, what makes an initializer list able to initialize members while the constructor itself can't?

CodePudding user response:

An initializer list always initializes all members. Full stop. Any members you fail to list have their default constructor called. If you reassign to them in the constructor body, then (in principle) you've just allocated and then immediately discarded one extra object.

In the particular case of const, a const variable cannot be reassigned to. It's never correct to set an initialized const variable equal to another value. It can only be initialized the first time, never reassigned.

struct Foo {
  const int x;
  int y;
  int z;

  Foo() : x(0), y(0) {
    // At this point, all three variables (even z) have been initialized.

    y = 0; // Okay, reassignment is fine but wasteful
    z = 0; // Same as above
    x = 0; // Error! Can't reassign to a const
  }

}
  • Related