Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Aggregate initialization

Aggregate initialization initializes the elements of an aggregate, usually with a brace-enclosed list. Learn element ordering, omitted-member values, and the restrictions on designated initializers in C++23.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

T object{value1, value2};
T object = {value1, value2};
T object{.member1 = value1, .member2 = value2};

Aggregate initialization initializes an aggregate's elements. An aggregate is an array or a class without user-declared or inherited constructors, private or protected direct non-static data members or bases, or virtual functions or virtual bases. Writing {...} alone does not imply aggregate initialization: for other classes it can call a constructor.

In T object{value1, value2}; and T object = {value1, value2};, elements are considered in array index order or, for a class, with bases first and then members, each in declaration order. The appertainment rules determine whether a positional initializer clause applies to an element itself or, recursively, to one of its subelements. Successive clauses can therefore apply to subelements of the same top-level element. For example, given struct T { int a[2]; int b; };, T object{1, 2}; initializes a[0] to 1 and a[1] to 2; the omitted b is initialized to 0.

For a non-union aggregate, an omitted element uses its default member initializer, otherwise it is initialized from {}; for int, this produces 0. An omitted reference without a default initializer is an error.

In C++23, T object{.member1 = value1, .member2 = value2}; requires direct non-static member names in declaration order. Members may be skipped, but positional and designated initializers cannot be mixed. List-initialization prohibits narrowing conversions, such as int{1.5}.

Entry scope: C++23. The supplied pages present an evolving working draft whose later extensions are not necessarily part of C++23. A repository compiler flag does not attest the production runtime environment.

Examples

#include <iostream>

struct Point {
    int x;
    int y = 10;
    int z;
};

int main() {
    Point a{3};
    Point b{.x = 4, .z = 8};
    std::cout << a.x << ' ' << a.y << ' ' << a.z << '\n';
    std::cout << b.x << ' ' << b.y << ' ' << b.z << '\n';
}

Result

3 10 0
4 10 8

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources