Aggregate initialization simplifies the initialization of objects with nested structures by allowing you to provide values in a nested list. This method is particularly useful for initializing complex types in a concise and readable manner.
Consider the following example with nested structures:
#include <iostream>
struct Point {
int x, y;
};
struct Line {
Point start, end;
};
int main() {
Line myLine{{0, 0}, {10, 10}};
std::cout << "Start: (" << myLine.start.x
<< ", " << myLine.start.y << ")\n";
std::cout << "End: (" << myLine.end.x
<< ", " << myLine.end.y << ")\n";
}
Start: (0, 0)
End: (10, 10)
In this example, Line
is an aggregate that contains two Point
objects. Using aggregate initialization, we can initialize myLine
with nested braces. Each Point
structure is initialized with its own list of values.
Aggregate initialization also works with more complex nesting:
#include <iostream>
#include <string>
struct Address {
std::string city, country;
};
struct Person {
std::string name;
int age;
Address address;
};
int main() {
Person p{"Alice", 30, {"New York", "USA"}};
std::cout << p.name << ", "
<< p.age << ", "
<< p.address.city << ", "
<< p.address.country;
}
Alice, 30, New York, USA
Here, the Person
structure contains a nested Address
structure. Aggregate initialization allows us to initialize the Person
object in a single statement, providing a list of values for each nested structure.
Aggregate initialization is convenient for initializing complex types, as it maintains readability and reduces boilerplate code.
However, it is essential to ensure that the structures being initialized are aggregates, meaning they do not have private or protected members, non-public base classes, or user-provided constructors.
Answers to questions are automatically generated and may not have been reviewed.
A quick guide to creating objects using lists, including std::initializer_list
, aggregate and designated initialization