Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ initialize anonymous struct

I'm still earning my C++ wings; My question is if I have a struct like so:

struct Height
{
    int feet;
    int inches;
};

And I then have some lines like so:

Height h = {5, 7};
Person p("John Doe", 42, "Blonde", "Blue", h);

I like the initialization of structs via curly braces, but I'd prefer the above be on one line, in an anonymous Height struct. How do I do this? My initial naive approach was:

Person p("John Doe", 42, "Blonde", "Blue", Height{5,7});

This didn't work though. Am I very far off the mark?

like image 271
dreadwail Avatar asked Oct 26 '10 04:10

dreadwail


2 Answers

You can't, at least not in present-day C++; the brace initialization is part of the initializer syntax and can't be used elsewhere.

You can add a constructor to Height:

struct Height
{
    Height(int f, int i) : feet(f), inches(i) { }
    int feet, inches;
};

This allows you to use:

Person p("John Doe", 42, "Blonde", "Blue", Height(5, 7));

Unfortunately, since Height is no longer an aggregate, you can no longer use the brace initialization. The constructor call initialization is just as easy, though:

Height h(5, 7);
like image 192
James McNellis Avatar answered Nov 10 '22 00:11

James McNellis


Standard C++ (C++98, C++03) doesn't support this.

g++ supports is a language extension, and I seem to recall that C++0x will support it. You'd have to check the syntax of the g++ language extension and/or possibly C++0x.

For currently standard C++, just name the Height instance, as you've already done, then use the name.

Cheers & hth.,

like image 20
Cheers and hth. - Alf Avatar answered Nov 10 '22 01:11

Cheers and hth. - Alf