What is a member initializer list, and why is it preferred over assignment in the constructor body?
Last updated
A member initializer list is the : member(value), ... syntax after the constructor signature that initializes members directly, before the constructor body runs. It's preferred because it constructs each member once, instead of default-constructing then reassigning.
Initialization vs. assignment:
In the list, the member is built with the given value in one step.
In the body, the member is already default-constructed, then
operator=overwrites it: two operations, often wasteful.
When it's mandatory:
constmembers and reference members: they can only be initialized, never assigned.Members with no default constructor, and base-class subobjects.
Gotcha: order: Members initialize in declaration order, not the order written in the list; mismatches can cause use-before-init bugs.
[lang:cpp]
class Point {
const int id;
int x, y;
public:
Point(int i, int a, int b)
: id(i), x(a), y(b) {} // id MUST be here; others built once
};