Topic: Can structs within classes be initialized w
Author: clamage@taumet.Eng.Sun.COM (Steve Clamage)
Date: 22 Jun 1994 17:17:24 GMT Raw View
In article li6@f111.iassf.easams.com.au, rjl@f111.iassf.easams.com.au (Rohan LENARD) writes:
>
>Compare the initialisation of a struct within and out of a class -
>
>
>// Struct outside of class
>struct Thing {
> double a;
> int b;
>};
>
>Thing blob = { 10.0, -1 };
OK, because this is an "aggregate", (what we now call a PODS).
>// Struct inside of class ?
>class Foo {
>public:
> Foo() : ClassBlob({10.0, -1}) {};
> // or should it be
> // Foo() : ClassBlob({double(10.0),int(-1)}) {};
Neither of these should be accepted. The mem-initializer requires an
epression inside the parens, and expressions do not contain braces.
The extra casts are irrelevent; 10.0 is already type double, and -1
is already type int.
>Is it possible to initialise ClassBlob like I have above, or not.
>
>The ARM seems to suggest that it is possible, but then both compilers I tried
>say it isn't.
I don't believe you can find a syntax production that allows this.
If you want to initialize the struct (as opposed to assigning to it)
give it a constructor:
struct Thing {
double a;
int b;
Thing(double d, int i) : a(d), b(i) { }
};
Thing blob(10.0, -1); // instead of "= {10.0, -1};"
Foo::Foo() : ClassBlob(10.0, -1) { ... }
I think the result is easier to read and write, as well as allowing you
to initialize a Thing easily no matter where it occurs -- even anonymous
temps.
---
Steve Clamage, stephen.clamage@eng.sun.com