c++constructorinitializationmember-initialization

What does it mean by member initialization list initializing an attribute of a class


If I have a class like the below one:

class foo {
  private:
    int a;
  public:
    foo (int arg1) : a(arg1) {}
};

The attribute a will be default-initialized in the line it got declared. Now, when the parameterized constructor is called, it gets re-initialized to the value arg1 in the member-initialization list.

  1. Is my understanding correct that a gets re-initialized in the member initialization list?
  2. If yes, what does it mean by an attribute getting re-initialized (Initialization means memory getting allocated. Now, what does re-initialization mean?)?

Solution

  • No, a won't be "re-initialized", i.e. initialized twice. When the parameterized constructor is used a will only be direct-initialized from the constructor parameter arg1, no default-initialization happens.

    If foo has another constructor which doesn't initialize a in member-init-list, then it'll be default-initialized. E.g.

    class foo {
      private:
        int a;
      public:
        foo (int arg1) : a(arg1) {} // a is direct-initialized from arg1 when this constructor used
        foo () {}                   // a is default-initialized when this constructor used
    };