Loading lessons...
Member Initializer Lists
Member Initializer Lists
Instead of assigning members inside the constructor body, you can initialize them in a member initializer list - a colon after the parentheses, followed by each member and its starting value:
class Car {
public:
string brand;
int year;
Car() : brand("Toyota"), year(2022) {
// the body can stay empty
}
};
- The colon comes right after the constructor's parentheses.
- Each entry is
member(value). - Entries are separated by commas.
Why it matters
Without the list you do two jobs: the member is first default-constructed, then assigned. With the list the member is constructed directly with the value. Fewer steps - which is why it is often more efficient, especially for strings and class-type members.
const members need it
A const member cannot be assigned after construction, so it must be initialized in the list:
class Box {
public:
const int size;
Box(int s) : size(s) { }
};
TL;DR
- Syntax:
Car() : brand("Toyota"), year(2022) { }. - Members are constructed directly instead of default-then-assign.
- That direct building is more efficient.
const(and reference) members must be initialized there.