views:

120

answers:

2

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?

+10  A: 

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);
James McNellis
Neat. I didn't know structs could have constructors/initializer-lists.
byte
@byte: A `struct` is exactly the same thing as a `class`. The only difference is that the base classes and members are by default public for a `struct` and private for a `class`.
James McNellis
+2  A: 

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.,

Alf P. Steinbach
Is it automatically provided, or do you have to define a constructor that accepts an `initializer_list` argument?
Ben Voigt
@Ben: no, you don't have to define a constructor to get the C++0x syntax. much of the point/goal is to have a *uniform* syntax that works the same in most every situation. check out the [Wikipedia link](http://en.wikipedia.org/wiki/C%2B%2B0x#Uniform_initialization) given by @sbi earlier. Or, if you want the details, the latest draft is available from the [C++ committe pages](http://www.open-std.org/jtc1/sc22/wg21/), in PDF format.
Alf P. Steinbach