c++ 20 struct initialization

The C++20 standard introduces a new way to initialize struct objects using designated initializers. This allows you to initialize specific members of a struct using their names, instead of relying on the order of the members.

Here are the steps to initialize a struct using designated initializers:

  1. Define the struct: Start by defining the struct using the struct keyword, followed by the struct name and its members. For example:
struct Person {
    std::string name;
    int age;
    std::string occupation;
};
  1. Initialize the struct: To initialize the struct using designated initializers, enclose the initialization values within curly braces {}. Inside the braces, specify the name of the member followed by a colon : and the value assigned to that member. For example:
Person p = { .name = "John Doe", .age = 30, .occupation = "Engineer" };

In this example, the member name is initialized with the value "John Doe", the member age is initialized with the value 30, and the member occupation is initialized with the value "Engineer".

  1. Access the struct members: Once the struct is initialized, you can access its members using the dot . operator. For example:
std::cout << "Name: " << p.name << std::endl;
std::cout << "Age: " << p.age << std::endl;
std::cout << "Occupation: " << p.occupation << std::endl;

This will output:

Name: John Doe
Age: 30
Occupation: Engineer

By using designated initializers, you can initialize specific members of a struct in any order, making the code more readable and less error-prone. It also allows you to omit the initialization of certain members, in which case they will be default-initialized.

Note that designated initializers are only available in C++20 and later versions. If you are using an older version of C++, you will need to use the traditional member initialization syntax.