Aggregate Initialization in C++

Level 5572 keystrokes

Aggregates (structs without constructors) are initialized with braces in member order; members left out use their default member initializers. C++20 designated initializers (.name = ...) name the members explicitly, and nested braces build a vector of Person inside Team.

C++ code

1struct Person {
2 string name;
// Default member initializers, used when a value is not given
3 int age = 0;
4 string city = "Unknown";
5};
6
// An aggregate that contains a vector of Person
7struct Team {
8 string name;
9 vector<Person> members;
10};
11
// Values are assigned in member order: name, age, city
12Person p1 = {"Alice", 30, "Tokyo"};
// city is omitted, so it stays "Unknown"
13Person p2 = {"Bob", 25};
// Designated initializers (C++20) must follow declaration order
14Person p3 = {.name = "Carol", .age = 35};
15
// Nested braces: the inner list builds the vector of two Person objects
16Team team = {"Engineering", {{"Dave", 28, "NYC"}, {"Eve", 32, "LA"}}};
17
// Prints "Alice, 30, Tokyo"
18cout << p1.name << ", " << p1.age << ", " << p1.city << endl;
// Prints "Bob, 25, Unknown"
19cout << p2.name << ", " << p2.age << ", " << p2.city << endl;
// Prints "Carol, 35, Unknown"
20cout << p3.name << ", " << p3.age << ", " << p3.city << endl;
// Prints "Team: Engineering (2 members)"
21cout << "Team: " << team.name << " (" << team.members.size() << " members)" << endl;

Output

Alice, 30, Tokyo
Bob, 25, Unknown
Carol, 35, Unknown
Team: Engineering (2 members)
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 49
  • "× 38
  • ,× 16
  • ;× 15
  • .× 14
  • {× 9
  • }× 9
  • =× 8
  • (× 2
  • )× 2

More C++ examples at level 5

← C++ typing practice