# Constructors & Member Initialization Order

> Follow the deterministic sequence of base-class, member, and destructor execution—and avoid initializer reordering traps, virtual dispatch bugs, and accidental non-aggregates.

- **Source:** C++ Atlas (https://cppatlas.com/topics/constructors-and-initialization-order)
- **Track:** Classes
- **Estimated reading time:** 8 minutes
- **ISO C++ clauses:** [class.ctor] (https://eel.is/c++draft/class.ctor), [class.base.init] (https://eel.is/c++draft/class.base.init), [class.dtor] (https://eel.is/c++draft/class.dtor), [class.cdtor] (https://eel.is/c++draft/class.cdtor), [except.ctor] (https://eel.is/c++draft/except.ctor), [dcl.init.aggr] (https://eel.is/c++draft/dcl.init.aggr)
- **cppreference links:** [Constructors and member initializer lists](https://en.cppreference.com/w/cpp/language/initializer_list), [Default constructors](https://en.cppreference.com/w/cpp/language/default_constructor), [Converting constructor](https://en.cppreference.com/w/cpp/language/converting_constructor), [explicit specifier](https://en.cppreference.com/w/cpp/language/explicit), [Destructors](https://en.cppreference.com/w/cpp/language/destructor), [Derived classes](https://en.cppreference.com/w/cpp/language/derived_class)
- **Prerequisites:** initialization-forms, copy-and-move, copy-elision

Every object in C++ follows a single, rigid construction script. Whether a class has one `int` or a diamond inheritance hierarchy, the compiler never follows the order you type in a constructor's member initializer list. Instead, `[class.base.init]/13` locks construction to the **declaration order** in the class definition so that every constructor shares one fixed destruction reverse order.

> **Mental model.** A constructor's member initializer list supplies *arguments*, not *execution order*. Every object is assembled bottom-up—virtual bases, direct bases, declared members, then body—and torn down in the exact mirror sequence when its lifetime ends.

## The invariant initialization order

For any non-delegating constructor of a class `D`, initialization executes in four mandatory stages (`[class.base.init]/13`):

| Phase | Subobjects initialized | Order rule | Destruction order (`~D`) |
| --- | --- | --- | --- |
| 1 | Virtual base classes | Depth-first, left-to-right in the inheritance DAG | Runs **4th** (very last) |
| 2 | Direct non-virtual base classes | Left-to-right in the base-specifier list | Runs **3rd** |
| 3 | Non-static data members | Top-to-bottom declaration order in class body | Runs **2nd** |
| 4 | Constructor compound body `{ ... }` | Statements inside `D::D(...)` | `~D` body runs **1st** (before subobjects) |

Two subtleties stand out in diamond hierarchies. First, **the most-derived class owns every virtual base**: when `Derived` inherits from `Left` and `Right` (which both inherit virtually from `VBase`), `Derived`'s constructor invokes `VBase`'s initializer directly—or default-initializes `VBase` if `Derived` omits it—while `Left` and `Right`'s initializers for `VBase` are skipped completely. Second, if a member has both a default member initializer (`int n = 42;`) and a mem-initializer (`: n(7)`), the mem-initializer wins and the default member initializer is ignored without double work.

```cpp
#include <iostream>

struct VBase {
    explicit VBase(int x) { std::cout << "VBase(" << x << ") "; }
    virtual ~VBase() = default;
};

struct Left : virtual VBase {
    Left() : VBase(1) { std::cout << "Left "; } // VBase(1) skipped by Derived!
};

struct Right : virtual VBase {
    Right() : VBase(2) { std::cout << "Right "; } // VBase(2) skipped by Derived!
};

struct Derived : Left, Right {
    int first = (std::cout << "first ", 10);
    int second;

    // Even if written in reverse order, VBase -> Left -> Right -> first -> second -> body:
    Derived() : VBase(99), Left(), Right(), second(first + 1) {
        std::cout << "Derived\n";
    }
};
```

## The mem-initializer order trap and initialization vs. assignment

Because member order always obeys declaration order inside the class body, reordering members in a mem-initializer list creates silent use-before-initialization bugs.

> **Pitfall.** Writing `struct Buffer { int* data; std::size_t cap; Buffer(std::size_t n) : cap(n), data(new int[cap]) {} };` has undefined behavior. Because `data` is declared before `cap`, `data(new int[cap])` runs *first*, reading an uninitialized `cap` before `cap(n)` executes. Always keep mem-initializers in exact declaration order and enable `-Wreorder`.

Always initialize members in the mem-initializer list rather than assigning inside `{ ... }`. A member constructed in `{ name_ = std::move(s); }` is **default-constructed first** during Phase 3 and then **move-assigned** during Phase 4—wasting work and failing to compile altogether for `const` members, reference members (`T&`), and types without default constructors.

## Delegating constructors and inherited constructors

C++11 added **delegating constructors** so one constructor can forward to another (`Widget() : Widget(0) { ... }`). A delegating constructor cannot mention any base or member in its initializer list—the target constructor owns all of Phases 1 through 3.

Delegating introduces an important exception-handling rule (`[except.ctor]/3`):

- In a **non-delegating** constructor, throwing inside the constructor body unwinds only already-constructed bases and members; the class's own destructor `~Widget()` does *not* run because the object never finished constructing.
- In a **delegating** constructor, the object's lifetime is considered to have **begun as soon as the target constructor returns**. If the delegating constructor's own body throws afterward, `~Widget()` *does* execute during stack unwinding.

You can also pull base-class constructors into a derived class with `using Base::Base;` (`[namespace.udecl]`), which generates matching forwarding constructors in `Derived` while still initializing `Derived`'s own data members via their default member initializers.

## Virtual dispatch during construction and destruction

Inside a base constructor or destructor, the dynamic type of `*this` is temporarily the base class currently executing, never the final derived class (`[class.cdtor]/4`).

> **Standardese.** "When a virtual function is called directly or indirectly from a constructor or from a destructor, including during the construction or destruction of the class's non-static data members, and the object to which the call applies is the object under construction or destruction, the function called is the final overrider in the constructor's or destructor's class and not one overriding it in a more-derived class." — `[class.cdtor]`

That guarantee prevents a base constructor from touching `Derived` member variables whose constructors have not started yet (or whose destructors have already finished). Calling a **pure virtual** function directly (or implicitly without overriding it in the current class) from a constructor or destructor is undefined behavior—pass configuration values as constructor arguments or invoke a two-phase helper after construction instead.

```cpp
struct Base {
    Base() { init_log(); } // Always calls Base::init_log(), never Derived::init_log()!
    virtual const char* kind() const { return "Base"; }
    void init_log() const { (void)kind(); }
    virtual ~Base() = default;
};

struct Derived : Base {
    int payload = 42;
    const char* kind() const override { return "Derived"; }
};
```

## Special rules: explicit, defaulted, and aggregate traps

Three modern constructor rules save subtle diagnostics once you know them:

1. **Mark converting constructors `explicit`.** Any non-explicit constructor callable with one argument acts as an implicit conversion (`void take(Span); take(10);`). Since C++11, `explicit` also blocks copy-list-initialization with multiple arguments (`return {1, 2};`), and C++20 added conditional `explicit(bool)` (`explicit(!std::is_convertible_v<T, U>)`) for wrapper templates like `std::pair` and `std::optional`.
2. **User-declared constructors suppress defaults.** Declaring *any* constructor—even `Widget(int)`—suppresses the implicitly declared default constructor unless you explicitly write `Widget() = default;`.
3. **C++20 tightened aggregate rules.** Prior to C++20, writing `Point() = default;` kept `Point` an aggregate. Starting in C++20 (`[dcl.init.aggr]/1`), **any user-declared constructor**—even `= default` or `= delete`—removes aggregate status, breaking `{1, 2}` aggregate initialization unless you omit the constructor declaration entirely or provide a matching constructor.

```cpp
#include <type_traits>

struct AggregatePoint {
    int x = 0;
    int y = 0;
};

struct NonAggregatePoint {
    int x = 0;
    int y = 0;
    NonAggregatePoint() = default; // User-declared: disables aggregate init in C++20+!
};

static_assert(std::is_aggregate_v<AggregatePoint>);
static_assert(!std::is_aggregate_v<NonAggregatePoint>);

AggregatePoint p1{1, 2}; // Valid aggregate initialization
// NonAggregatePoint p2{1, 2}; // Error in C++20+: no matching constructor
```

## What to remember

- **Declaration order rules construction.** Virtual bases run first, then direct bases left-to-right, then non-static data members top-to-bottom, ignoring mem-initializer order.
- **Destruction is exact LIFO.** Destructors unwind bodies, members, direct bases, and finally virtual bases in strict reverse construction order.
- **Virtual calls stay in the active class.** Inside `Base::Base()` or `Base::~Base()`, `*this` has dynamic type `Base`, never `Derived`.
- **Delegating completes object lifetime early.** Once the target constructor finishes, throwing in the delegating body triggers `~T()`.
- **Watch `explicit` and C++20 aggregates.** Use `explicit` on single- and multi-argument constructors to stop silent conversions, and omit `= default` constructors when you want aggregate brace initialization.

## Concept Map Outline

- **Constructors & Init Order:** Object construction and destruction follow fixed declaration-order phases regardless of initializer list order.
  - **Strict Subobject Sequence:** Every non-delegating constructor assembles subobjects in four rigid standard-mandated phases.
    - **1. Virtual bases first:** The most-derived class initializes all virtual bases once depth-first left-to-right.
    - **2. Direct bases left-to-right:** Non-virtual direct base classes construct in the order listed on the class header.
    - **3. Members in declaration order:** Non-static data members initialize top-to-bottom as declared in the class body.
    - **4. Constructor body runs last:** The compound statement executes only after every base and member has been constructed.
  - **Mem-Initializer Rules:** Member initializer lists supply construction arguments without altering initialization order.
    - **Initializer order is ignored:** Reordering members in a colon list still runs them in declaration order, risking uninitialized reads.
    - **Init beats body assignment:** Initializing members directly avoids default-constructing then reassigning and handles const or ref fields.
    - **Default member initializers:** Inline member initializers serve as fallbacks skipped whenever a mem-initializer names that member.
  - **Destruction & Exceptions:** Teardown mirrors construction in reverse and handles partially built or delegated objects carefully.
    - **Exact reverse teardown:** Destructors run their body first, then members, direct bases, and virtual bases in reverse.
    - **Partial build unwinds subobjects:** Throwing in a non-delegating constructor destroys built subobjects without calling ~Class().
    - **Delegating completes lifetime:** Once a target constructor finishes, throwing in the delegating body invokes ~Class().
  - **Virtual Dispatch Hazard:** Polymorphic dispatch treats the object under construction or destruction as its current class.
    - **Dynamic type is current class:** Virtual calls inside Base::Base() resolve to Base overriders, never Derived.
    - **Pure virtual call is UB:** Invoking an unimplemented pure virtual during construction or destruction causes undefined behavior.
  - **Special & Aggregate Rules:** Constructor declarations govern implicit conversions, default generation, and C++20 aggregate eligibility.
    - **explicit stops silent conversions:** Use explicit and C++20 explicit(bool) to prevent unwanted scalar or braced conversions.
    - **User ctor drops default:** Declaring any custom constructor suppresses the implicitly generated default constructor.
    - **C++20 aggregate restriction:** Any user-declared constructor, even = default, disqualifies a type from aggregate initialization.

## Standardese Quiz Questions

### Question 1 [warmup] ([class.base.init])

Why does `Buffer(std::size_t n) : cap(n), data(new int[cap]) {}` exhibit undefined behavior?

```cpp
struct Buffer {
    int* data;
    std::size_t cap;
    Buffer(std::size_t n) : cap(n), data(new int[cap]) {}
};
```

A. `new int[cap]` cannot appear inside a member initializer list.
B. `std::size_t` cannot be converted inside an initializer list.
C. `data` is declared before `cap`, so `data` initializes first and reads an uninitialized `cap`.
D. Member initializer lists evaluate strictly right-to-left.

**Answer (C):** `data` is declared before `cap`, so `data` initializes first and reads an uninitialized `cap`.

**Why:** Under `[class.base.init]/13`, non-static data members always initialize in declaration order inside the class body (`data`, then `cap`), ignoring the order written in the colon initializer list. `data(new int[cap])` reads indeterminate `cap` before `cap(n)` runs.

### Question 2 [warmup] ([class.base.init])

When constructing a `std::string` member `name_` from a parameter, why should you prefer `: name_(std::move(s))` over `name_ = std::move(s);` in the constructor body?

A. The member initializer constructs `name_` once in place instead of default-constructing it first and then move-assigning.
B. Assignment inside a constructor body is forbidden for standard library types.
C. `std::move` only works inside member initializer lists.
D. Member initializers skip calling `~std::string()` at destruction.

**Answer (A):** The member initializer constructs `name_` once in place instead of default-constructing it first and then move-assigning.

**Why:** Every member not named in the mem-initializer list is initialized before entering the constructor body (`[class.base.init]/9`), so assigning inside `{ ... }` performs default construction followed by assignment. Mem-initializers construct once directly and are mandatory for `const`, reference, and non-default-constructible members.

### Question 3 [tricky] ([class.cdtor])

Given `Base::Base()` calling `virtual const char* kind() const`, what does `Derived d;` cause `Base::Base()` to observe when `Derived` overrides `kind()`?

```cpp
struct Base {
    Base() { std::cout << kind(); }
    virtual const char* kind() const { return "Base"; }
    virtual ~Base() = default;
};
struct Derived : Base {
    const char* kind() const override { return "Derived"; }
};
Derived d;
```

A. "Derived", because the vptr already points to `Derived`'s vtable.
B. Undefined behavior whenever any virtual function is called from a constructor.
C. Compile error: virtual functions cannot be called inside constructors.
D. "Base", because during `Base::Base()` the dynamic type of the object is `Base`.

**Answer (D):** "Base", because during `Base::Base()` the dynamic type of the object is `Base`.

**Why:** Under `[class.cdtor]/4`, while a base constructor or destructor is executing, the object's dynamic type is that base class (`Base`), not the still-uninitialized `Derived` class. Virtual dispatch resolves to `Base::kind()`.

### Question 4 [tricky] ([class.base.init])

In a virtual-inheritance diamond `struct Derived : Left, Right`, where `Left() : VBase(1)` and `Right() : VBase(2)` and `Derived() : Left(), Right()` omits `VBase`, how is `VBase` initialized?

```cpp
struct VBase { VBase(int x = 0); };
struct Left : virtual VBase { Left() : VBase(1) {} };
struct Right : virtual VBase { Right() : VBase(2) {} };
struct Derived : Left, Right { Derived() : Left(), Right() {} };
```

A. `VBase(1)` runs via `Left`, and `Right`'s `VBase(2)` is skipped.
B. `Derived` acts as the most-derived class and default-initializes `VBase(0)`, ignoring both `Left` and `Right`'s `VBase` initializers.
C. Compile error: `Derived` must explicitly repeat `VBase(1)` or `VBase(2)`.
D. `VBase` is constructed twice—once with `1` and once with `2`.

**Answer (B):** `Derived` acts as the most-derived class and default-initializes `VBase(0)`, ignoring both `Left` and `Right`'s `VBase` initializers.

**Why:** `[class.base.init]/7` specifies that virtual base classes are initialized solely by the most-derived class (`Derived`), ignoring `VBase(...)` mem-initializers in intermediate bases `Left` and `Right`. Because `Derived` omitted `VBase`, `VBase` is default-initialized with `0`.

### Question 5 [standardese] ([except.ctor])

If a delegating constructor finishes calling its target constructor and then throws inside its own compound body `{ ... }`, does `~Widget()` execute?

```cpp
struct Widget {
    Widget(int) {}
    Widget() : Widget(0) { throw 1; }
    ~Widget();
};
```

A. No; `~Widget()` never executes if any constructor throws.
B. Only if `Widget(int)` was marked `noexcept`.
C. Yes; once the target constructor completes, the object's lifetime has begun so `~Widget()` runs during unwinding.
D. Undefined behavior unless caught inside a function-try-block.

**Answer (C):** Yes; once the target constructor completes, the object's lifetime has begun so `~Widget()` runs during unwinding.

**Why:** Unlike a non-delegating constructor (where throwing destroys only constructed subobjects), `[except.ctor]/3` states that an object whose constructor delegates is considered fully constructed once the target constructor returns normally. Therefore throwing in the delegating body invokes `~Widget()`.

### Question 6 [standardese] ([dcl.init.aggr])

Why does `Point p{1, 2};` fail to compile in C++20 and C++23 when `Point` declares `Point() = default;`?

```cpp
struct Point {
    int x;
    int y;
    Point() = default;
};
Point p{1, 2};
```

A. `= default` makes `Point` trivial rather than initializable with braces.
B. In C++20+, any user-declared constructor—even `= default` or `= delete`—disqualifies a class from being an aggregate.
C. Aggregate initialization only works when all members have default member initializers.
D. `Point()` must be declared `constexpr` to support `{1, 2}`.

**Answer (B):** In C++20+, any user-declared constructor—even `= default` or `= delete`—disqualifies a class from being an aggregate.

**Why:** Prior to C++20, defaulted or deleted constructors did not prevent a class from being an aggregate. C++20 (`[dcl.init.aggr]/1`) changed the definition so *any* user-declared or inherited constructor makes the class a non-aggregate, leaving `Point p{1, 2}` with no matching two-argument constructor.
