Uniform initialization in C++

Initializing in C++98 used to be a pain:

  • There were multiple ways to initialize: using = or () or {}.

  • Some types of initialization of user types was either difficult or not possible to support.

  • You could not initialize variable of a builtin type to its default value (like in Java). C or C++ only default-initialize in global scope, not in non-global scope.

  • No way to initialize a container (like std::vector or your own) with a series of non-default values.

C++11 introduced an uniform initialization syntax using {} that makes writing and reading C++ a joy! In my opinion, this is a feature that will make everyone’s code easier to write and read. Though it does have a few rough edges (since C++ has to support all previous syntaxes), it almost always works in a way that is most intuitive to the viewer.

It is called uniform initialization because it is applicable in every place where you initialize anything. That includes: variables, constants, objects, in the initializer list of a constructor and even in the member declaration of a struct or class. Everywhere!

I am sharing a code sample below that enumerates the various ways to apply this syntax:

Tried with: GCC 5.1 and Ubuntu 14.04


4 thoughts on “Uniform initialization in C++

  1. Note, that a narrowing conversion in this case is ill-formed and the compiler is required to generate a diagnostic but the diagnostic could be an error or a warning. There are several versions of gcc where this is only a warning.


      1. Well cppreference gives a good summary http://en.cppreference.com/w/cpp/language/list_initialization#Narrowing_conversions . In a Stackoverflow answer I quote the gcc bug report that explains why some versions of gcc made it warning as opposed to an error: http://stackoverflow.com/a/31685448/1708801 . In that answer I cite the relevant sections from the draft C++11 standard as well as link to it. The C++ standard is always the best reference.

        This quote from Herb Sutter in another Stackoverflow answer on the same topic http://stackoverflow.com/questions/16939471/preventing-narrowing-conversion-when-using-stdinitializer-list#comment24463587_16939798 is a good read.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.