A C++ Connection constructor lists bufferSize_ before buffer_ in its initializer list, yet buffer_ is sized from garbage; why?
answer
- the list's order is ignored
- declaration order rules
- reverse order on destruction
- -Wreorder in -Wall
basics
~20 sMembers are initialised in the order they are declared in the class, not the order of the initializer list. buffer_ is declared first, so buffer_(bufferSize_) reads bufferSize_ before it is initialised, which is undefined behaviour.
solid answer
~40 sThe standard says non-static data members are initialised in the order they were declared in the class definition, regardless of the order of the mem-initializers; direct bases likewise follow the base-specifier-list. If `Connection` declares `std::vector<char> buffer_;` above `std::size_t bufferSize_;`, then `buffer_(bufferSize_)` runs first and reads an uninitialised `std::size_t`, which is undefined behaviour, so the buffer may get any size or the program may crash. The rule exists so destruction can run in exactly the reverse order of construction. Compilers warn: with `-Wall`, Clang reports `field 'bufferSize_' will be initialized after field 'buffer_' [-Wreorder-ctor]` and `field 'bufferSize_' is uninitialized when used here`, and GCC's `-Wreorder` is also enabled by `-Wall`. Fix it by initialising from the constructor parameter, by reordering the declarations, and by always writing the list in declaration order.
code
cpp · 22 lines#include <cstdio>
#include <string>
#include <vector>
class Connection {
public:
Connection(std::string host, std::size_t bufferSize)
: host_(std::move(host)),
bufferSize_(bufferSize),
buffer_(bufferSize) {} // sized from the parameter, not the member
std::size_t capacity() const { return buffer_.size(); }
std::size_t bufferSize() const { return bufferSize_; }
private:
std::string host_;
std::size_t bufferSize_; // declared before buffer_: initialised first
std::vector<char> buffer_;
};
int main() {
Connection c("db.local", 4096);
std::printf("%zu %zu\n", c.capacity(), c.bufferSize());
}go deeper
Recall that members are initialised in declaration order, whatever the initializer list says.
Explain why the rule exists, a single reverse destruction order, and read the -Wreorder-ctor and uninitialised-use warnings correctly.
Treat the read of an uninitialised member as undefined behaviour, remove the dependency by initialising from parameters, and keep -Wall warnings fatal in CI.
Weigh reordering declarations against layout and ABI constraints, and make declaration-order lists a lint-enforced convention across the codebase.
## The rule In C++ the **member initializer list** says *how* each member is initialised, never *when*. The standard fixes the order for a non-delegating constructor: 1. Virtual base classes, in a depth-first left-to-right traversal of the base graph. 2. Direct base classes, in the order they appear in the base-specifier-list, regardless of the order of the mem-initializers. 3. Non-static data members, in the order they were declared in the class definition, again regardless of the order of the mem-initializers. 4. The constructor body. The standard's own note gives the reason: the declaration order is mandated so that base and member subobjects are destroyed in the reverse order of initialisation. A class can have many constructors with lists in different orders, but only one destructor, so construction must follow one fixed order that the destructor can reverse. ## The Connection bug ```cpp class Connection { public: Connection(std::string host, std::size_t bufferSize) : host_(std::move(host)), bufferSize_(bufferSize), buffer_(bufferSize_) {} // reads bufferSize_ too early private: std::string host_; std::vector<char> buffer_; // declared before bufferSize_ std::size_t bufferSize_; }; ``` The list reads naturally from top to bottom, but `buffer_` is declared before `bufferSize_`, so `buffer_(bufferSize_)` runs second, after `host_`, while `bufferSize_` still holds an indeterminate value. Reading it is **undefined behaviour**: the vector may be sized from whatever bits were in memory, allocation may fail with `std::bad_alloc` or `std::length_error`, or the optimiser may assume the read never happens. No output of such a run means anything. ## What the compilers say Apple clang 21 with `-Wall` reports both halves of the problem: ```plaintext order.cpp:9:11: warning: field 'bufferSize_' will be initialized after field 'buffer_' [-Wreorder-ctor] order.cpp:10:19: warning: field 'bufferSize_' is uninitialized when used here [-Wuninitialized] ``` In Clang, `-Wreorder-ctor` is part of `-Wreorder`, which `-Wall` enables. GCC's manual says its `-Wreorder` warning is enabled by `-Wall` as well. Projects that build with `-Werror` turn the mismatch into a hard error, which is one reason teams keep `-Wall` on. ## Fixing it Three fixes, best first: - **Initialise from the parameter**, not from another member: `buffer_(bufferSize)`. This removes the dependency, so the order no longer matters for correctness. - **Reorder the declarations** so a member that others depend on is declared first. This changes the class layout, which matters if the type's size, padding or ABI is fixed. - **Write every initializer list in declaration order**, so the code reads in the order it runs and the warning stays quiet. The code example applies the first two: `bufferSize_` is declared before `buffer_`, and `buffer_` is sized from the parameter. It prints `4096 4096`. ## Related traps | Situation | What actually happens | |---|---| | Member initialised from a member declared later | reads an uninitialised object: undefined behaviour | | Two base classes listed in a different order in the mem-initializers | bases still initialised in base-specifier order | | Member initialised from a base class's member | safe: bases are initialised before members | | Default member initializer refers to a member declared earlier | safe: the earlier member is already initialised | | Destructor of a member uses another member | members are destroyed in reverse declaration order, so later members are already gone | The last row is the mirror image of the bug: a member declared earlier outlives those declared after it, so a member whose destructor needs another member should be declared after it. ## Catching it in review Warnings catch the textbook case, but not every variant: - A member read through a **member function call** in the list, such as `buffer_(computeSize())` where `computeSize()` reads a later member, is not always diagnosed. - A **default member initializer** that refers to a member declared after it has the same problem; Clang's `-Wuninitialized` flags the simple case, but reviewers miss it because no constructor mentions it. - Adding a new member in the **middle** of a class silently changes the order for every constructor. The durable habit is to make each initializer depend only on constructor parameters, constants and members declared above it. ## How to answer State the rule (declaration order, not list order), the reason (one destruction order), the symptom (an uninitialised read, which is undefined behaviour), and the tools (`-Wall` warnings). Then show the fix that removes the dependency rather than just reshuffling lines.
- Why does C++ ignore the order of the member initializer list instead of following it?Because a class can have many constructors, each with its own list, but only one destructor. Members must be destroyed in the reverse order of their construction, so construction has to follow one order that does not depend on which constructor ran. The standard's note says the declaration order is mandated for exactly this reason.
- In C++, is it safe to initialise a member from a base class's member in the initializer list?Yes, for a non-virtual base that is fully constructed: all direct bases are initialised before any non-static data member, whatever the list order says. Calling a virtual function of the object during that phase is a separate question, covered with virtual calls in constructors.
A building goes up floor by floor in the order of the blueprint, whatever order the contractor's checklist names the floors in; a checklist that fits the third-floor windows using measurements from a fourth floor not yet built gets nonsense.
- Members are initialised in the order written in the initializer list.
- Reading the not-yet-initialised member just gives zero.
- The compiler silently reorders the list, so the order never matters.
- Reordering the initializer list fixes the bug without touching anything else.
- Base classes are initialised after the members listed before them.