# Aggregates and designated initializers

> An aggregate is a type the compiler initializes member by member with no constructor in charge. Its definition was rewritten in every standard from C++11 to C++20, and C++20 added designated initializers, parenthesized aggregate initialization and deduction for aggregate templates.

- **Source:** C++ Atlas (https://cppatlas.com/topics/aggregates-and-designated-initializers)
- **Track:** Types and initialization
- **Estimated reading time:** 12 minutes
- **ISO C++ clauses:** [dcl.init.aggr] (https://eel.is/c++draft/dcl.init.aggr), [dcl.init.general] (https://eel.is/c++draft/dcl.init.general), [dcl.init.list] (https://eel.is/c++draft/dcl.init.list), [class.temporary] (https://eel.is/c++draft/class.temporary), [over.match.class.deduct] (https://eel.is/c++draft/over.match.class.deduct)
- **cppreference links:** [Aggregate initialization](https://en.cppreference.com/w/cpp/language/aggregate_initialization), [List-initialization](https://en.cppreference.com/w/cpp/language/list_initialization), [std::is_aggregate](https://en.cppreference.com/w/cpp/types/is_aggregate), [Class template argument deduction](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction)
- **Prerequisites:** initialization-forms, reference-binding-and-temporaries

## The one idea

An aggregate is a type with no constructor in charge of it. Initializing one does not call a function that decides what the members become. Instead the compiler walks the elements in declaration order, bases first and then non-static data members, and copy-initializes each one from the next initializer you supplied. Elements you leave out get their default member initializer if they have one, and are otherwise initialized from an empty brace list, which for scalars means zero.

That is why aggregates are attractive and why the rules are strict. Any feature that would let the class itself take part in initialization, such as a constructor, a virtual function or a private data member, disqualifies the type.

> **Mental model.** An aggregate is a list of named slots. Aggregate initialization fills the slots in order from your list and value-initializes the rest. No function of the class runs to decide anything, so there is nothing for access control or a constructor to enforce.

## What counts as an aggregate, standard by standard

Arrays are always aggregates. For classes the definition has moved in every revision, and code that compiled under one rule changes meaning under the next.

| Standard | What a class aggregate may not have |
| --- | --- |
| C++11 | user-provided constructors, default member initializers, private or protected non-static data members, base classes, virtual functions |
| C++14 | the same, except default member initializers are now allowed |
| C++17 | user-provided, explicit or inherited constructors; private or protected non-static data members; virtual functions; virtual, private or protected bases |
| C++20 | user-declared or inherited constructors; private or protected non-static data members; virtual functions; virtual, private or protected bases |

Several things never stopped a type from being an aggregate: member functions, static data members of any access, a user-declared destructor, and user-declared assignment operators. A lambda's closure type is explicitly not an aggregate. When in doubt, ask the compiler: the C++17 trait `std::is_aggregate_v<T>` reports the answer under whatever language mode you compile with, and a `static_assert` on it protects a type whose users depend on brace initialization.

The C++20 change, from P1008, closed a loophole. Before it, a class with a deleted or private defaulted constructor was still an aggregate, so braces bypassed the constructor entirely.

```cpp
struct NoDefault {
  NoDefault() = delete;
  int x;
};

// NoDefault n{};
// C++17: compiles, aggregate initialization ignores the deleted constructor
// C++20: ill-formed, the type has a user-declared constructor, so {} calls it
```

> **Pitfall.** Adding `S() = default;` to a struct in C++20 silently makes it a non-aggregate. `S{1, 2}` then stops compiling, because there is no constructor taking two arguments. Prefer default member initializers to a defaulted constructor when you want both defaults and aggregate syntax.

## Aggregate initialization and brace elision

Each element is copy-initialized from its initializer, so an explicit constructor of a member type cannot be used to convert it, and since the initializer is a braced list, narrowing is ill-formed. A reference member with no initializer and no default member initializer makes the program ill-formed. For a union, aggregate initialization initializes only the first member, unless a designator names another. Inside any braced list the initializer clauses are evaluated strictly left to right, each one sequenced before the next, which is a stronger guarantee than function arguments get.

```cpp
struct Opts {
  int a;
  int b = 5;
  int c;
};

Opts o{1};   // a is 1, b is 5 from its default member initializer, c is 0
```

When an element is itself an aggregate, its braces can be omitted. Brace elision lets the initializers flow into the subaggregate's elements in order, which is how `int m[2][2] = {1, 2, 3, 4};` and `std::array<int, 3> a = {1, 2, 3};` work: `std::array` is a struct wrapping a built-in array, and the inner braces are elided. Elision is only assumed when an initializer cannot initialize the element directly, and it breaks down when you write some braces but not all of them.

```cpp
#include <array>

struct P { int x, y; };

std::array<P, 2> ok1{{{1, 2}, {3, 4}}};   // all braces written
std::array<P, 2> ok2{P{1, 2}, P{3, 4}};   // each element is a P expression
// std::array<P, 2> bad{{1, 2}, {3, 4}};
// ill-formed: {1, 2} initializes the inner P[2] array, then {3, 4} is
// an extra initializer for a struct with one member
```

## Bases are elements too (C++17)

Since C++17 an aggregate may have public, non-virtual base classes. Each base is an element that comes before the data members, and it is initialized like any other element, with its own braces or through brace elision.

```cpp
struct Base { int b; };
struct Derived : Base { int d; };

Derived x{{1}, 2};   // x.b is 1, x.d is 2
Derived y{1, 2};     // the same, by brace elision
```

Because the base subobject is now initialized directly by aggregate initialization, rather than by `Derived`'s implicit constructor, access checks happen in the context of the code doing the initialization. A base with a protected default constructor used to work and now does not.

```cpp
struct Guarded { protected: Guarded() = default; };
struct Open : Guarded {};

Open a;      // fine: Open's implicit default constructor may call it
// Open b{};
// fine in C++14, where Open was not an aggregate;
// ill-formed since C++17: Guarded() is initialized from {} outside the class
```

## Designated initializers (C++20)

C++20 lets you name the members you initialize: `P p{.x = 1, .y = 2};`. The feature looks like C's, but it is deliberately narrower.

- Designators must appear in declaration order. C allows any order; GCC rejects out-of-order designators and Clang accepts them with a warning.
- Either every initializer clause is designated or none is. You cannot write `{.x = 1, 2}`.
- Only direct non-static data members can be named. There are no nested designators such as `.inner.y`, no array designators such as `[2] = 5`, and no way to name a base class.
- Each member may be designated at most once.

Members you skip are initialized as in ordinary aggregate initialization, from their default member initializer or from `{}`. For a union, a designator selects which member becomes active, and only one may be given.

```cpp
struct Inner { int y; };
struct Outer { int x; Inner in; int z = 7; };
union Num { int i; float f; };

Outer a{.x = 1, .in{2}};    // z is 7
Outer b{.in = {3}};         // x is 0, z is 7
Num n{.f = 1.5f};           // f is the active member
// Outer c{.z = 1, .x = 2}; // ill-formed: out of declaration order
// Outer d{.x = 1, 2};      // ill-formed: mixes designated and positional
```

Designators combined with default member initializers give C++ something close to named arguments. A function taking an options struct by value can be called with only the fields that differ from the defaults, and the names document the call site. Designated lists also take part in overload resolution: [over.ics.list] allows a designated list to convert to a parameter only if that parameter's aggregate type can be initialized from it, so the designator names select the overload.

```cpp
#include <string>

struct Conn { std::string host; int port = 80; int timeout = 30; };
int connect(Conn c) { return c.port + c.timeout; }

struct ByName { int name; };
struct ById   { int id; };
int find(ByName) { return 1; }
int find(ById)   { return 2; }

int a = connect({.host = "db", .timeout = 5});   // port stays 80
int b = find({.id = 7});                         // calls find(ById)
```

> **Standardese.** [dcl.init.aggr] defines the explicitly initialized elements of a designated list as exactly the named members, requires the designators to name members in declaration order, and initializes every other element as if no designator were present. Compilers accept several C forms as extensions; pass `-pedantic` to have them flagged.

## Parenthesized aggregate initialization (C++20)

P0960 made `T(args...)` work for aggregates. When no constructor matches, which for an aggregate means always unless it is a single argument of the same type, the elements are initialized from the parenthesized list. That is what lets `std::make_unique<P>(1, 2)` and `v.emplace_back(1, 2)` construct aggregates, since library code spells construction with parentheses. Arrays work too: `int a[](1, 2, 3);` declares three ints.

The two spellings are not interchangeable. Parentheses do not forbid narrowing, do not perform brace elision, and do not accept designators. Most importantly, a temporary bound to a reference member is not lifetime-extended.

```cpp
struct Ref { const int& r; };

constexpr int braces() { Ref a{42}; return a.r; }
static_assert(braces() == 42);   // the temporary lives as long as a

// constexpr int parens() { Ref b(42); return b.r; }
// static_assert(parens() == 42);
// rejected: the temporary died at the end of the declaration of b,
// so reading b.r is undefined behavior
```

> **Pitfall.** [class.temporary] lists a temporary bound to a reference element of an aggregate initialized from a parenthesized list as an exception to lifetime extension. `Ref b(42);` compiles and leaves `b.r` dangling, while `Ref a{42};` is safe.

## Deduction for aggregate templates (C++20)

Class template argument deduction normally works from constructors and deduction guides, which an aggregate template does not have. In C++17 you had to write a guide by hand, as `std::array` does. C++20 adds an aggregate deduction candidate, synthesized from the element types, so `Pair p{1, 2.0};` deduces `Pair<int, double>`. GCC 16 and Clang 21 also use it for the parenthesized form `Pair p(1, 2.0);`.

```cpp
#include <type_traits>

template <class T, class U>
struct Pair { T first; U second; };

Pair p{1, 2.0};   // C++20: Pair<int, double>, no guide needed
static_assert(std::is_same_v<decltype(p), Pair<int, double>>);
```

The class-template-argument-deduction topic covers how the candidate set is built and how brace elision interacts with it.

## What to remember

- An aggregate is an array or a class whose initialization no constructor controls; its elements are bases, then data members.
- C++14 allowed default member initializers, C++17 allowed public bases, and C++20 banned every user-declared constructor.
- Omitted elements use their default member initializer, otherwise they are initialized from `{}`.
- Brace elision lets inner braces disappear, but `std::array<P, 2>{{1, 2}, {3, 4}}` fails; write all braces or none.
- Since C++17 a base's protected default constructor makes `Derived{}` ill-formed.
- Designators must follow declaration order, cannot be mixed with positional clauses, and cannot nest or index.
- Parenthesized aggregate init allows narrowing and does not extend the lifetime of temporaries bound to reference members.
- C++20 deduces template arguments for aggregate templates without deduction guides.

## Concept Map Outline

- **Aggregates:** Types initialized element by element, with no constructor in charge.
  - **Definition by version:** Arrays always qualify; the class rules changed in every standard since C++11.
    - **C++14:** Default member initializers no longer disqualify a class.
    - **C++17:** Public non-virtual bases allowed; explicit or inherited constructors disqualify.
    - **C++20:** Any user-declared constructor, even = default or = delete, disqualifies.
    - **Never disqualifying:** Member functions, statics, a user-declared destructor and assignment operators.
  - **Aggregate initialization:** Elements, bases first, are copy-initialized in order from the list.
    - **Omitted elements:** Use the default member initializer, otherwise are initialized from {}.
    - **No narrowing:** Braced aggregate initialization rejects narrowing conversions.
    - **Unions:** Without a designator only the first member is initialized.
    - **Brace elision:** Inner braces may be dropped; {{1,2},{3,4}} fails for std::array<P,2>.
  - **Base classes (C++17):** Each public base is an element initialized before the data members.
    - **Derived{{1}, 2}:** The base gets its own braces, or brace elision fills it.
    - **Protected base ctor:** Derived{} is ill-formed since C++17: the base is initialized from outside.
  - **Designated (C++20):** Name members with .x = value, a deliberately narrow subset of C.
    - **Declaration order:** Designators must follow member order, unlike C.
    - **All or none:** Designated and positional clauses cannot be mixed.
    - **No nesting or indices:** No .a.b, no [2] = x, and bases cannot be named.
    - **Union member choice:** A single designator picks the union's active member.
  - **Parentheses (C++20):** T(args...) aggregate-initializes when no constructor is viable.
    - **Library construction:** make_unique<P>(1, 2) and emplace_back(1, 2) now work for aggregates.
    - **Narrowing allowed:** N n(2.5) compiles and truncates, while N n{2.5} is ill-formed.
    - **No lifetime extension:** A temporary bound to a reference member dies at the end of the declaration.
  - **CTAD for aggregates:** C++20 synthesizes a deduction candidate from the element types.
    - **No guide needed:** Pair p{1, 2.0} deduces Pair<int, double> without a deduction guide.

## Standardese Quiz Questions

### Question 1 [warmup] ([dcl.init.aggr], [dcl.init.list])

In C++20, is the declaration of `n` well-formed?

```cpp
struct NoDefault {
  NoDefault() = delete;
  int x;
};

int main() {
  NoDefault n{};
  (void)n;
}
```

A. Yes: `NoDefault` is an aggregate, so `{}` never calls the constructor
B. Yes: `n.x` is zero-initialized
C. No: the type is not an aggregate, so `{}` calls the deleted default constructor
D. Yes in C++20, but it was ill-formed in C++17

**Answer (C):** No: the type is not an aggregate, so `{}` calls the deleted default constructor

**Why:** Since C++20 (P1008) a class with any user-declared constructor is not an aggregate, and a deleted constructor is user-declared. Empty braces on a class with a default constructor value-initialize, which selects the deleted constructor, so the program is ill-formed. The first option was true in C++11 through C++17, where only user-provided constructors disqualified a type, so the code compiled; the last option has the history backwards.

### Question 2 [warmup] ([dcl.init.aggr], [dcl.init.general])

In C++20, is this declaration well-formed?

```cpp
struct P { int x, y; };

P p{.y = 1, .x = 2};
```

A. No: designators must appear in declaration order
B. Yes: `p.x` is 2 and `p.y` is 1, as in C
C. Yes: the values are applied positionally, so `p.x` is 1
D. Yes, but the order in which `x` and `y` are initialized is unspecified

**Answer (A):** No: designators must appear in declaration order

**Why:** C++20 designated initializers must name members in the order they are declared, so this is ill-formed. C accepts any order, which makes the second option tempting, and Clang accepts it as an extension with a `-Wreorder-init-list` warning; GCC rejects it. The rule exists so that initializers are evaluated in the same order as members are initialized.

### Question 3 [warmup] ([dcl.init.aggr])

What does this program print?

```cpp
#include <cstdio>

struct Opts {
  int a;
  int b = 5;
  int c;
};

int main() {
  Opts o{1};
  std::printf("%d %d %d\n", o.a, o.b, o.c);
}
```

A. `1 0 0`
B. Nothing useful: `o.c` is indeterminate, so the behavior is undefined
C. It does not compile: `c` needs an initializer
D. `1 5 0`

**Answer (D):** `1 5 0`

**Why:** `Opts` is an aggregate (default member initializers are allowed since C++14). Elements without an initializer use their default member initializer, so `b` is 5, and otherwise are copy-initialized from an empty initializer list, which zeroes `c`. The indeterminate answer would be right for `Opts o;`, which default-initializes, but any brace list makes every element initialized.

### Question 4 [tricky] ([dcl.init.aggr], [array.overview])

Is the declaration of `a` well-formed?

```cpp
#include <array>

struct P { int x, y; };

std::array<P, 2> a{{1, 2}, {3, 4}};
```

A. Yes: it creates `P{1, 2}` and `P{3, 4}`
B. No: `{1, 2}` initializes the inner array, so `{3, 4}` is an excess initializer
C. Yes, but `a[1]` is value-initialized and `{3, 4}` is ignored
D. No: `std::array` cannot be initialized from nested braces

**Answer (B):** No: `{1, 2}` initializes the inner array, so `{3, 4}` is an excess initializer

**Why:** `std::array<P, 2>` is a struct whose single element is a built-in `P[2]`. The first clause `{1, 2}` is a braced list, so it initializes that inner array, as `P[2]{1, 2}`, filling `a[0]`. The second clause has no element left to initialize, so the program is ill-formed. Brace elision only helps when you elide all the inner braces, `{1, 2, 3, 4}`, or write all of them, `{{{1, 2}, {3, 4}}}`.

### Question 5 [tricky] ([class.temporary], [dcl.init.general])

In C++20, what does the standard say about this program?

```cpp
struct Ref { const int& r; };

int main() {
  Ref a{42};
  Ref b(42);
  return a.r + b.r;
}
```

A. It returns 84
B. It is ill-formed: an aggregate with a reference member cannot be initialized with parentheses
C. The behavior is undefined: `b.r` refers to a temporary that has been destroyed
D. The behavior is undefined: both `a.r` and `b.r` dangle

**Answer (C):** The behavior is undefined: `b.r` refers to a temporary that has been destroyed

**Why:** Both declarations are aggregate initialization; the parenthesized form is valid since C++20. With braces, the temporary bound to the reference member is lifetime-extended to the lifetime of `a`. [class.temporary] makes an exception for an aggregate initialized from a parenthesized expression-list, so the temporary behind `b.r` dies at the end of that declaration and reading it is undefined behavior. That asymmetry is why the first option is so tempting.

### Question 6 [tricky] ([dcl.init.aggr], [class.protected])

In C++20, is the declaration of `b` well-formed?

```cpp
struct Guarded { protected: Guarded() = default; };
struct Open : Guarded {};

int main() {
  Open b{};
  (void)b;
}
```

A. No: `Open` is an aggregate, and `Guarded()` is not accessible where the base is initialized
B. Yes: `Open`'s implicit default constructor calls `Guarded()`
C. Yes: a derived class may always call a protected base constructor
D. It is implementation-defined

**Answer (A):** No: `Open` is an aggregate, and `Guarded()` is not accessible where the base is initialized

**Why:** Since C++17 a class with a public base can be an aggregate, so `Open{}` is aggregate initialization and the base element is copy-initialized from `{}` in the context of `main`, where the protected constructor is inaccessible. The program is ill-formed. Before C++17 `Open` was not an aggregate and its implicit constructor called `Guarded()` from inside the derived class, which is what the second option describes; `Open b;` still works that way.

### Question 7 [standardese] ([dcl.init.aggr], [expr.prim.lambda.closure])

Which of these is an aggregate in C++20?

A. `struct A { private: int x; };`
B. `struct B { B() = default; int x; };`
C. The closure type of `[] {}`
D. `struct D : Base { int d; void f(); ~D(); };` where `Base` is a class with only public members

**Answer (D):** `struct D : Base { int d; void f(); ~D(); };` where `Base` is a class with only public members

**Why:** Member functions and a user-declared destructor never disqualify a class, and since C++17 a public non-virtual base is allowed, so `D` is an aggregate. A private non-static data member disqualifies `A`. `B` has a user-declared constructor, which disqualifies it since C++20 even though it is defaulted, the tempting answer for anyone who learned the C++17 rule. The standard states outright that a closure type is not an aggregate.

### Question 8 [standardese] ([over.match.class.deduct])

In C++20, with no deduction guides declared, what is `decltype(p)`?

```cpp
template <class T, class U>
struct Pair { T first; U second; };

Pair p{1, 2.0};
```

A. The declaration is ill-formed: there is no constructor or guide to deduce from
B. `Pair<int, double>`
C. `Pair<double, double>`
D. `Pair<int, int>`

**Answer (B):** `Pair<int, double>`

**Why:** C++20 adds an aggregate deduction candidate: for an aggregate class template, the compiler synthesizes a candidate whose parameters are the element types, so `T` deduces from `1` and `U` from `2.0`. In C++17 deduction failed here unless you wrote a guide, which is the first option and the reason `std::array` ships with one.
