Aggregate Classes
Aggregate classes are a special type of class characterized by their members being directly initialized using brace initializers.
Let’s take a look at the following example:
1
2
3
4
5
6
7
8
struct Point {
int x;
int y;
};
Point p{50,100};
In the simple struct above, it can be directly initialized using braces:
Point p{50,100};
Before C++17, aggregate classes had to meet the following conditions:
- No user-defined constructors (including default constructors).
- No private or protected non-static data members.
- No virtual functions.
- No base classes. These restrictions made aggregate classes typically simple data structures like structs or classes, with many limitations!
C++17 relaxed the definition of aggregate classes, allowing the following:
- Can have base classes, as long as the base classes are also aggregate classes and do not have private or protected non-static data members (relaxation of condition 4 above).
- Can have non-static data members (including objects and references) (relaxation of condition 2 above).
Let’s look at some code
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
class Base {
public:
int base_val;
};
class Derived : public Base {
public:
std::string derived_val;
};
Execution result in C++14
Execution result in C++17
Benefits
Simplified Initialization: Using aggregate initialization makes the code more concise! That’s it! 就這樣!



