C++11 List Initialization

Image

C++11 introduces a new variable initialization syntax. List initialization (also called uniform initialization) enables you to use one syntax to initialize a variable of any type. Consider line 11 of Fig. 4.12

unsigned int studentCounter = 1;

In C++11, you can write this as

unsigned int studentCounter = { 1 };

or

unsigned int studentCounter{ 1 };

The braces ({ and }) represent the list initializer. For a fundamental-type variable, you place only one value in the list initializer. For an object, the list initializer can be a comma-separated list of values that are passed to the object’s constructor. For example, consider an Employee class that contains an employee’s first name, last name and salary. Assuming the class defines a constructor that receives strings for the first and last names and a double for the salary, you could initialize Employee objects as follows:

Employee employee1{ "Bob", "Blue", 1234.56 };
Employee employee2 = { "Sue", "Green", 2143.65 };

For fundamental-type variables, list-initialization syntax also prevents so-called narrowing conversions that could result in data loss. For example, previously you could write

int x = 12.7;

which attempts to assign the double value 12.7 to the int variable x. A double value is converted to an int, by truncating the floating-point part (.7), which results in a loss of information—a narrowing conversion. The actual value assigned to x is 12. Many compilers generate a warning for this statement, but still allow it to compile. However, using list initialization, as in

int x = { 12.7 };

or

int x{ 12.7 };

yields a compilation error, thus helping you avoid a potentially subtle logic error. For example, Apple’s Xcode LLVM compiler gives the error

Type 'double' cannot be narrowed to 'int' in initializer list

We’ll discuss additional list-initializer features in later chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.252.199