Home Item 21 - Aggregate Classes (English)
Post
Cancel

Item 21 - Aggregate Classes (English)

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:

  1. No user-defined constructors (including default constructors).
  2. No private or protected non-static data members.
  3. No virtual functions.
  4. 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:

  1. 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).
  2. 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;
};

Here is the main function: Desktop View

Execution result in C++14

Desktop View

Execution result in C++17

Desktop View

Benefits

Simplified Initialization: Using aggregate initialization makes the code more concise! That’s it! 就這樣!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍