0

The following code compiles fine in g++.

#include <iostream>
#include <string>
using namespace std;

struct thing
{
    int a;
    char b;
    string name;
};

int main()
{
    thing t =
    {
        a : 23,
        b : 'e',
        name : "Hello"
    };

    cout << t.a << endl;
    cout << t.b << endl;
    cout << t.name << endl;

    return 0;
}

I know that the C99 equivalent { .a = 23, .b = 'e', .name = "Hello" } is not supported in C++, but why is the above supported? Is it standardised? What is the name of this constructor idiom?

To put the above in perspective, if you have a system with a lot of immutable classes used for thread-safe messaging (all const and public members), then it is much easier to construct an instance of such a class using named members rather than writing a constructor and using positional arguments.

magnus
  • 4,031
  • 7
  • 26
  • 48
  • 1
    "*Is it standardised?*" No. – Nicol Bolas Mar 08 '18 at 05:10
  • 1
    Guilherme's answer covers this case well. https://stackoverflow.com/questions/11516657/c-structure-initialization – murfito Mar 08 '18 at 05:17
  • 1
    It looks [obsolete GCC extension](https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html): "Another syntax that has the same meaning, obsolete since GCC 2.5, is ‘fieldname:’" – kakkoko Mar 08 '18 at 06:16
  • @kakkoko Yes, it looks obsolete. Clang also supports it but a warning is produced. It’s a shame because constructor-only initialisation makes sense for behaviour-rich, invariant-holding classes, but sometimes a plain-old data structure with no behaviour is all you need. In which case, designated initialisers make a lot of sense syntactically. – magnus Mar 08 '18 at 08:56

0 Answers0