C++ Question Initializing a struct.

Hlynkacg

Aspiring rocket scientist
Addon Developer
Tutorial Publisher
Donator
Joined
Dec 27, 2010
Messages
1,870
Reaction score
3
Points
0
Location
San Diego
In 'C' as well as a few other languages you can fill an array or struct via the following or something similar.

Code:
struct foo = {value 1, value 2, value 3, etc...};

however this does not appear to work in C++. Long story short I would like to know why this works.

Code:
strobe = new BEACONLIGHTSPEC;
strobe->shape = BEACONSHAPE_STAR;
strobe->pos = &strobe_pos;
strobe->col = &strobe_color;
strobe->size = 0.5;
strobe->falloff = 0.2;
strobe->period = 1.0;
strobe->duration = 0.02;
strobe->tofs = 0.0;
strobe->active = true;

AddBeacon (strobe);

but this does not,

Code:
strobe = new BEACONLIGHTSPEC {BEACONSHAPE_STAR, &strobe_pos, &strobe_color, 0.5, 0.2, 1.0, 0.02, 0.0, true};
AddBeacon (strobe);

and if there is a more efficient way to initialize/fill an existing struct than setting the values individually.

note that in both cases "strobe" is a class variable, ie "BEACONLIGHTSPEC *strobe;"
 

Urwumpe

Not funny anymore
Addon Developer
Donator
Joined
Feb 6, 2008
Messages
37,641
Reaction score
2,356
Points
203
Location
Wolfsburg
Preferred Pronouns
Sire
Well, you can always use an inline factory method of course in C++ as alternative. Or the constructor for classes.

But the initialization you want to do (automatically assign values to struct during heap memory allocation) does not work in C11 as well.

As quick example from your code:

Code:
inline BEACONLIGHTSPEC * NEWBEACONLIGHTSPEC(FOO *strobe_pos, BAR *strobe_color) {
    BEACONLIGHTSPEC *strobe = new BEACONLIGHTSPEC;
    strobe->shape = BEACONSHAPE_STAR;
    strobe->pos = strobe_pos;
    strobe->col = strobe_color;
    strobe->size = 0.5;
    strobe->falloff = 0.2;
    strobe->period = 1.0;
    strobe->duration = 0.02;
    strobe->tofs = 0.0;
    strobe->active = true;

    return strobe;
};
 
Last edited:

meson800

Addon Developer
Addon Developer
Donator
Joined
Aug 6, 2011
Messages
405
Reaction score
2
Points
18
Code:
strobe = new BEACONLIGHTSPEC {BEACONSHAPE_STAR, &strobe_pos, &strobe_color, 0.5, 0.2, 1.0, 0.02, 0.0, true};
AddBeacon (strobe);

Are you using C++11? That should work...

In pre C++11, afaik you have to do
Code:
BEACONLIGHTSPEC temp = { BEACONSHAPE_STAR, &strobe_pos, &strobe_color, 0.5, 0.2, 1.0, 0.02, 0.0, true };
AddBeacon(new BEACONLIGHTSPEC(temp));

Of course, both of those fail if there is a defined constructor/copy assignment/etc instead of the default ones.
 
Top