Unified Initialization with {}
In this lesson, we will learn how to initialize variables using {}.
We'll cover the following
The initialization of variables became uniform in C++11. For unified initialization, we need the {}
brackets.
{}
initialization is always applicable.
Direct initialization #
Variables can be declared directly without the assignment operator:
std::string str{"my String"};
int i{2011};
Copy initialization #
{}
also supports copy initialization with the =
operator:
std::string str = {"my String"};
int i = {2011};
The difference is that direct initialization directly calls the constructor of the type, whereas, in copy initialization, the value is created and implicitly converted into the type.
Preventing narrowing #
Narrowing, or more precisely narrowing conversion, is an implicit conversion of arithmetic values from one type to another. This can cause a loss of accuracy, which can be extremely dangerous.
The following example shows the issue with the classical way of initializing fundamental types.
The compiler presents a warning, yet the implicit conversions are performed nonetheless, resulting in data loss.
It doesn’t matter whether we use direct initialization or assignment:
Create a free account to view this lesson.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy