In C++, why initialise members in a constructor's member initializer list rather than assigning them in the constructor body?
answer
- members exist before the body
- construct once, not twice
- const, references, no default constructor
- default member initializers fill gaps
basics
~20 sEvery member is initialised before the constructor body runs, so body assignment means construct, then assign. The initializer list constructs each member once, and is the only way to initialise const members, references and members lacking a default constructor.
solid answer
~50 sBy the time a constructor's body starts, every base and member has already been initialised. A member missing from the member initializer list gets its default member initializer if it has one, otherwise default-initialisation: a `std::string` is constructed empty, an `int` is left with an indeterminate value. Assigning in the body therefore does the work twice for class types, and for some members it is impossible: a `const int`, a reference member and a member whose type has no default constructor must appear in the list, and Clang says so, for example `constructor for 'Connection' must explicitly initialize the const member 'id_'`. Default member initializers, such as `int retries_ = 3;`, give every constructor a fallback, and a constructor that names the member in its list overrides the default for that constructor only. The body is for work that needs a fully built object: validation, logging, registering `this` somewhere.
code
cpp · 22 lines#include <cstdio>
#include <string>
class Connection {
public:
Connection() = default; // every default member initializer
explicit Connection(int port) : port_(port) {} // port_ from the list, rest defaulted
Connection(std::string host, int port) : Connection(port) { // delegates, then runs its body
host_ = std::move(host);
}
void print() const { std::printf("%s:%d retries=%d\n", host_.c_str(), port_, retries_); }
private:
std::string host_ = "localhost";
int port_ = 5432;
int retries_ = 3;
};
int main() {
Connection().print();
Connection(6432).print();
Connection("db.internal", 7000).print();
}go deeper
Recall that members are initialised before the body runs, and that const members, references and members without default constructors must go in the initializer list.
Explain where each member's value comes from: the list, then the default member initializer, then default-initialisation, and why body assignment costs a second operation.
Spot indeterminate scalars and double construction in real constructors, and standardise on default member initializers so new constructors cannot forget a member.
Make default member initializers plus list initialisation a review rule, since it removes a class of uninitialised-read defects at no runtime cost.
## What happens before the body runs A C++ constructor has two parts: the **member initializer list** after the colon, and the **body** between the braces. The standard fixes the order of work for a non-delegating constructor: 1. Virtual base classes, then direct base classes, are initialised. 2. Non-static data members are initialised, in the order they are declared in the class. 3. Only then does the constructor's body execute. So when the body runs, every member already exists. A statement such as `host_ = host;` in the body is an **assignment** to an object that was constructed a moment earlier, not its initialisation. ## Where each member's initial value comes from For each non-static data member, the constructor picks exactly one source: - If the member is named in the **member initializer list**, that initializer is used. - Otherwise, if the member has a **default member initializer** (`int port_ = 5432;`), that is used. - Otherwise the member is **default-initialised**: class types run their default constructor, and scalars such as `int` or raw pointers are left with an indeterminate value. The standard states the tie-break explicitly: if a member has both a default member initializer and a mem-initializer, the mem-initializer is performed and the default member initializer is ignored. That makes default member initializers a convenient fallback shared by every constructor, with each constructor overriding only what it needs. ## Members that cannot be assigned later Three kinds of member make body assignment a compile error rather than a style issue. Apple clang 21 reports each one for a constructor that tries: ```plaintext error: constructor for 'Connection' must explicitly initialize the const member 'id_' error: constructor for 'Connection' must explicitly initialize the reference member 'log_' error: constructor for 'Connection' must explicitly initialize the member 'sock_' which does not have a default constructor ``` | Member kind | Can the body assign it? | What to do | |---|---|---| | `const int id_;` | no, it is const | initialise in the list, or give a default member initializer | | `const std::string& log_;` | no, a reference binds once | initialise in the list | | `Socket sock_;` with only `explicit Socket(int)` | no default construction first | initialise in the list | | `std::string host_;` | yes, but it was already built empty | prefer the list | | `int retries_;` | yes, but it was indeterminate until then | prefer a default member initializer | ## The cost of assigning in the body For a member such as `std::string` or `std::vector`, body assignment runs the default constructor and then the assignment operator, which may allocate, free and allocate again. Initialising in the list constructs the member once from the argument, and for a by-value parameter it can be moved in: `host_(std::move(host))`. For a scalar the cost is negligible, but the window in which it holds an indeterminate value is not: any code in the body that reads it before assigning it has undefined behaviour. ## Default member initializers in practice The code example gives `host_`, `port_` and `retries_` default member initializers and then: - `Connection()` uses all three defaults; - `explicit Connection(int port)` names only `port_`, so the other two keep their defaults; - `Connection(std::string host, int port)` delegates to the `int` constructor and then assigns `host_` in its body. It prints `localhost:5432 retries=3`, `localhost:6432 retries=3` and `db.internal:7000 retries=3`. The third constructor shows the cost of body assignment in miniature: `host_` is first built as `"localhost"` by the target constructor and then overwritten. ## What belongs in the body Use the body for work that needs a complete object: checking invariants across members, throwing when they fail, logging, or registering `this` with another component. Initialisation itself belongs in the list or in default member initializers, written in declaration order so the code reads the way it runs. ## Reviewing a constructor A quick review pass catches most initialisation defects: 1. Does every **scalar or raw-pointer member** have a default member initializer or a mem-initializer in every constructor? 2. Is any member of class type **assigned in the body** when it could be initialised in the list, possibly by moving a by-value parameter? 3. Does the list follow **declaration order**, so no initializer reads a member that has not been initialised yet? 4. Does the body only do work that needs the **whole object**, rather than initialisation in disguise?
- In C++, what value does an int member hold if the constructor neither lists it nor gives it a default member initializer?It is default-initialised, which for an `int` performs no initialisation, so its value is indeterminate. Reading it before assigning is undefined behaviour in C++23. Unless the object itself was value-initialised, as in `Connection c{};` with no user-provided default constructor, nothing zeroes it. A default member initializer such as `int retries_ = 3;` removes the hazard for every constructor at once.
- If a C++ member has a default member initializer and also appears in a constructor's initializer list, which one runs?Only the mem-initializer. The standard says the initialization specified by the mem-initializer is performed and the member's default member initializer is ignored. So the default member initializer is never evaluated for that constructor: no double construction and no side effects from the default expression.
- Members are initialised by the assignments in the constructor body.
- The initializer list is only a stylistic alternative with identical cost.
- A const member can be set once in the constructor body.
- A default member initializer runs first and the initializer list then overwrites it.
- Members left out of the initializer list are always zero-initialised.