...

/

Designated Initializers in C++20

Designated Initializers in C++20

The C++20 standard also gives us another handy way to initialize data members. The new feature is called designated initializers, and it might be familiar to C programmers.

The basics

In basic C++20 form, you can write:

Type obj = { .designator = val, .designator { val2 }, ... };

For example:

struct Point { double x; double y; };
Point p { .x = 10.0, .y = 20.0 };

Designator points to a name of a non-static data member from our class, like .x or .y.

One of the main reasons to use this new kind of initialization is to increase readability.

This is easier to read:

struct Date {
    int year;
    int month;
    int day;
};

Date inFuture { .year = 2050,
...