Jes
Jes

Reputation: 2694

C++ initialization list and constructor

C++14 provides the initialization list and we can use it to initialize elements in a class or struct. What are the differences of the two initialization manners in the following code?

struct MyItem {
  MyItem() : val{0} {}
  int val;
};

struct MyItem {
  MyItem() {}
  int val{0};
};

Upvotes: 4

Views: 133

Answers (1)

Brian Bi
Brian Bi

Reputation: 119562

In your case, there is no difference. The first case uses a mem-initializer to initialize val. The second uses a brace-or-equal-initializer. A brace-or-equal-initializer will be used for a member when there is no mem-initializer present for that member. If there is a mem-initializer, it takes precedence, and the brace-or-equal-initializer is ignored.

One can certainly construct contrived examples where there is a difference...

const int i = 42;

struct S1 {
    S1(int i): val{i} {} // sets val to the parameter i
    int val;
};

struct S2 {
    S2(int i) {} // param is ignored
    int val{i}; // sets val to 42
};

Upvotes: 4

Related Questions