General features: Uniform initialization

code

Syntax

Usage / Usability

Using braces, specifying the initial contents of a container is easy

Constructor calls with empty braces

  • No arguments ? => default construction
  • Empty initializer list ? => construction of init list with no elements

Calling a ctor with an empty initializer_list

  • You need to call the ctor with a empty braces

PROS

  • prohibits implicit narrowing conversions among built-in types.

If the value of an expression in a braced initializer isn’t guaranteed to be expressible by the type of the object being initialized, the code won’t compile:

  • Minimizes Redundant Writing

Pitfalls

Interference with other constructors

std::vector has a constructor that allows you to specify the initial size of the container and a value each of the initial elements should have.
std::vector also has a constructor taking a std::initializer_list that permits you to specify the initial values in the container.

 

QUIZ – Will it compile?

Answer: No! Ambiguous call.

Leave a comment

Your email address will not be published.