Reputation: 3418
I just came across this line of code:
SDL_Color textColor = { 255, 0, 255 };
It made me wonder why it can be declared like an array. I thought it might've just ment the same as textColor(255,0,255);
but it didnt work like that when I tried making my own class. Can anyone explain when this type of syntax is used? Where are the parameters going..?
Upvotes: 3
Views: 406
Reputation: 227370
It is aggregate initialization of a type, most likely a simple struct or class. For example,
struct Foo
{
int i,j;
double x,y;
};
int main()
{
Foo f = {1,2, 3.,4.};
}
Note since there is some confusion regarding structs
, the above example would also work with a class
, which in this case is identical to the struct
:
class Foo
{
public:
int i,j;
double x,y;
};
In C++11 this type of initialization is extended to non-aggregate types under certain conditions.
for example
std::vector<int> v = {1,2,3,4,5};
Upvotes: 10
Reputation: 8594
SDL_Color
is an aggregate (a struct
with 4 members, in this case).
You can initialize an aggregate (not just an array) using an initializer list.
SDL_Color textColor = { 255, 0, 255 };
is the same as
SDL_Color textColor;
textColor.r = 255;
textColor.g = 0;
textColor.b = 255;
textColor.unused = 0;
Upvotes: 1
Reputation: 476930
All aggregates can be brace-initialized, which initializes each aggregate member with the matching item. If the list contains fewer items than there are aggregate members, the remaining elements are initialized as though from an empty brace list.
Upvotes: 3