Member initializer lists
A member initializer list is the : name_(name), size_(size) clause between a constructor's signature and its body. It constructs each member directly with the value you want, instead of default-constructing it and then assigning over it.
Detailed Explanation
Every constructor initializes its members. The only question is whether you choose the values or the compiler picks defaults for you. The initializer list is where you choose.
Consider a session cache holding a std::string key. Assign inside the body and two things happen: the string is default-constructed to empty, then the assignment operator throws that away and copies your value in. Use the initializer list and the string is built from your value once. For a std::string or a std::vector that is a wasted allocation; for a member whose construction is expensive, it is twice the work for no benefit.
That is the performance argument. The correctness argument is stronger, because for three kinds of member the body is not an option at all:
constmembers. You cannot assign to aconst. The initializer list is the one moment its value can be set.- Reference members. A reference must be bound when it comes into existence and can never be rebound. Assigning through it modifies the referent instead.
- Members with no default constructor. There is nothing to construct first, so the compiler cannot even reach your body. The same applies to a base class that needs arguments — base initializers go in the same list, before the members.
Order is the classic trap. Members are initialized in the order they are declared in the class, and the order you write the initializer list is ignored. Write : total_(count_ * price_), count_(n) and, if count_ is declared after total_, you have read a member whose lifetime has not begun: undefined behavior, usually a plausible-looking garbage number. Compilers warn under -Wreorder or -Wall; keep the list in declaration order and the problem disappears.
Since C++11 there is a second place to put a value: a default member initializer written in the class body, as in int ttlSeconds_ = 60;. It applies to every constructor that does not override it in its list, which removes the duplication of repeating the same default across four constructors. A constructor's initializer list wins over the in-class default when both exist.
One naming collision deserves a warning, because the two things have nothing to do with each other. std::initializer_list<T> is a library type from <initializer_list>: a lightweight, read-only view over a braced sequence of values, which is what makes std::vector<int> v{1, 2, 3}; work. A constructor taking one lets your class be built from a brace list. It is unrelated to the : clause discussed here, and it brings its own hazard: once a class has an initializer_list constructor, brace initialization prefers it strongly, so std::vector<int> v{5, 0} is two elements while std::vector<int> v(5, 0) is five zeroes. The shared word "initializer list" is an accident of naming.
A last note on cost and style: initializer lists are the mechanism behind cheap construction, so prefer taking a parameter by value and std::move-ing it into the member for types like std::string. Members that are themselves RAII types then need nothing else from you.
Code Examples
#include <string>
#include <vector>
class Logger {
public:
// sink_ is a reference and prefix_ is const: neither can be assigned,
// so both must be initialized here.
Logger(std::vector<std::string>& sink, std::string prefix)
: sink_(sink), prefix_(std::move(prefix)) {} // one construction, no wasted copy
void write(const std::string& line) { sink_.push_back(prefix_ + line); }
private:
std::vector<std::string>& sink_; // declared first, so initialized first
const std::string prefix_;
int written_ = 0; // default member initializer, C++11
};#include <iostream>
#include <string>
struct Slow {
std::string text;
// Wrong: default-construct then assign. Two operations, and it would not
// compile at all if text were const or a reference.
explicit Slow(const std::string& t) { text = t; }
};
struct Ordered {
// Bug: total_ is declared before count_, so count_ is still uninitialized
// here regardless of the order written below. Undefined behavior.
explicit Ordered(int n) : count_(n), total_(count_ * 10) {}
int total_;
int count_;
};
int main() {
std::cout << Ordered(3).total_ << '\n'; // garbage, not 30
}Common Gotchas
Declaration order beats list order
the compiler initializes members top-to-bottom as declared. Initializing one member from another declared later reads an object before its lifetime starts, which is undefined behavior. Enable `-Wreorder`.
`const`, reference, and base-class members cannot wait for the body
if a member has no default constructor or cannot be assigned, omitting it from the list is a compile error, and the message often points at the class rather than the real cause.
A member can be initialized twice for free if you are careless
assigning in the body after the member was already built is legal but does double work. It shows up in profiles when the member is a container or a string.