[2026] C++ Aggregates & Aggregate Initialization | Practical Complete Guide
이 글의 핵심
What is an aggregate type, how brace initialization works, C++17/20 changes (bases, designated initializers), arrays, and production patterns for configs and tests.
Why aggregates matter
Aggregates let you skip constructors for simple “bags of data” and use brace initialization instead. 아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 코드를 직접 실행해보면서 동작을 확인해보세요.
struct Point {
int x;
int y;
};
int main() {
Point p = {10, 20};
}
Table of contents
- Aggregate conditions
- Basic syntax
- C++17/20 changes
- Arrays
- Common errors
- Production patterns
- Full example
1. Aggregate conditions (C++17-style summary)
- No user-provided constructors (per standard rules—verify with
is_aggregate) - No private/protected non-static data members
- No virtual functions
- No problematic base classes (see standard; public base allowed since C++17) 아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 코드를 직접 실행해보면서 동작을 확인해보세요.
struct Point { int x, y; }; // aggregate
struct Derived : Point { int z; }; // often aggregate (C++17+)
struct NotAgg {
virtual void f() {}
int x;
};
2. Basic syntax
아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
struct Person {
std::string name;
int age;
double height;
};
Person p1 = {"Alice", 30, 165.5};
Person p2 = {"Bob", 25}; // height value-initialized
Person p3 = {}; // all value-initialized
Person p4{"Charlie", 35, 180.0};
3. C++17/20
- C++17: aggregates may have public base classes.
- C++20: designated initializers
.member = value.
struct Point { int x, y, z; };
Point p = { .x = 10, .y = 20, .z = 30 };
4. Arrays
아래 코드는 cpp를 사용한 구현 예제입니다. 코드를 직접 실행해보면서 동작을 확인해보세요.
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5] = {1, 2};
int arr3[] = {1, 2, 3};
int matrix[2][3] = { {1,2,3}, {4,5,6} };
5. Common errors
- User-defined ctor → no longer aggregate brace list in the same way.
- Private members break aggregate rules.
- Too many initializers for members.
6. Production patterns
Configuration
아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
struct DatabaseConfig {
std::string host = "localhost";
int port = 5432;
std::string database = "mydb";
};
DatabaseConfig prod = {
.host = "prod.example.com",
.port = 5432,
.database = "production"
};
Test tables
아래 코드는 cpp를 사용한 구현 예제입니다. 클래스를 정의하여 데이터와 기능을 캡슐화하며. 각 부분의 역할을 이해하면서 코드를 살펴보시기 바랍니다.
struct TestData {
int input;
int expected;
std::string description;
};
std::vector<TestData> cases = {
{0, 0, "zero"},
{5, 25, "five squared"}
};
Summary
| Concept | Meaning |
|---|---|
| Aggregate | Simple type per standard rules |
| Init | Usually { ....} |
| C++17 | Bases allowed |
| C++20 | Designated initializers |
| Related: Initialization order. |