Named Initialization of Class Members

Get the details of designated initialization in C++20.

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

Press + to interact
#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 ...

Get hands-on with 1400+ tech skills courses.