Quiz Entry - updated: 2026.07.06
How do you define a constructor with an initializer list in C++?
After the constructor signature, list members with : member(value) before the body — e.g. Vehicle::Vehicle(int n) : _nwheels(n) {}.
ClassName::ClassName(int x)
: _member(x) // initializer list
{
// constructor body (can be empty)
}
Example:
Vehicle::Vehicle(int nwheels)
: _nwheels(nwheels)
{
}
Why use initializer lists?
- More efficient — members are initialized directly, instead of being default-constructed and then assigned in the body
- Required for
constmembers and references (they can only be initialized, never assigned) - Required for member objects that have no default constructor
Multiple members are comma-separated:
Point::Point(int x, int y)
: _x(x), _y(y)
{
}
Go deeper:
Constructors and member initializer lists — cppreference — the full rules, including initialization order.