Search⌘ K

Named Initialization of Class Members

Explore how to use designated initialization in C++20 to assign values directly to class members by name. Learn the constraints on initialization order, how default member values work, and key differences from C to write clear and correct aggregate initializations.

Designated initialization enables the direct initialization of members of a class type using their names. For a union, only one initializer can be provided. As for aggregate initialization, the sequence of initializers in the curly braces has to match the declaration order of the members.

Designated initialization

C++
#include <iostream>
struct Point2D {
int x;
int y;
};
class Point3D {
public:
int x;
int y;
int z;
};
int main() {
std::cout << '\n';
Point2D point2D{.x = 1, .y = 2};
Point3D point3D{.x = 1, .y = 2, .z = 3};
std::cout << "point2D: " << point2D.x << " " << point2D.y << '\n';
std::cout << "point3D: " << point3D.x << " " << point3D.y << " "
<< point3D.z << '\n';
std::cout << '\n';
}

Line 18 and 19 use designated initializers to initialize the aggregates. The initializers such as .x or .y are often called designators.

The members of the aggregate can already have ...