Search code examples
c++c++20designated-initializer

What is a Designated Initializer?


I wish to understand what designated initializers provide that is different to direct initialization.

For example:

#include <iostream>

struct Subject{

    int x;
    int y;
    int z;

};

int main()
{ 
    Subject subject_d{.x = 1, .y = 2, .z= 3};
    Subject subject_c{1, 2, 3};

    return 0;
}

How can we decorticate these two lines? For the meticulous ones, what is the difference?


Solution

  • In the example you posted, there's absolutely no difference in terms of the behavior. The aggregate is initialized to hold the same three values. In terms of readability, an argument can be made that the designated initializer version is more explicit in terms of what is happening. It can also be used to serve a documentation purpose. The intended meaning of each initializer (assuming we named the members well) is written right next to it.

    Beyond explicit-ness in initialization. Designated initializers also play nice with other C++ features. Consider instead.

    struct Subject{
        int x = 0;
        int y = 0;
        int z = 0;
    };
    

    You could write

    Subject const s { .y = 2 };
    

    We go with the default value for all fields except y. And the variable s is const, because we don't want it to change. It's good in terms of const correctness.

    You can achieve a similar effect without designated initializers, but it would involve a fair more boiler-plate if we want s to remain const, and would arguably not be as terse and clear. That's in a nut-shell why they are nice to have in the language.