Why do I have to use {} to initialize SDL_Rect, not ()?

The following way of initializing an SDL_Rect object will cause an error:
SDL_Rect r( 0, 0, 100, 100 );

But this does not:
SDL_Rect r{ 0, 0, 100, 100 };

So why do I have to use {} to initialize SDL_Rect, not ()? I’m using SDL 2.0 on Windows 10 + Visual Studio 2015. The error message is:

error C2440: ‘initializing’: cannot convert from ‘initializer list’ to ‘SDL_Rect’
note: No constructor could take the source type, or constructor overload resolution was ambiguous

SDL is a C, not C++, library. It can be used from C++, but it doesn’t support any C++-specific things.
SDL_Rect is just a simple C-struct, not a class, and doesn’t have a constructor that could be called with SDL_rect r( 0, 0, 100, 100 ); (no idea why MS VS considers that an initializer list though, that error message doesn’t make sense to me).

SDL_Rect r{ 0, 0, 100, 100 }; will just set the members of the SDL_Rect struct in the order they occur in the struct: x (=0), y (=0), w (=100), h (=100).
SDL_Rect r = { 0, 0, 100, 100 }; should also be valid (even in plain C, while the form without = is C++-only I think)

1 Like

Yes, in C++ it is called aggregate initialization.

However, the syntax without = is only available since C++11. SDL_Rect r
= {1, 2, 3, 4} is both C and C++ compatible (any version).

1 Like