Andrue
Andrue

Reputation: 707

C++11 Variable Initialization and Declaration

With C++11 came a new way to initialize and declare variables.

Original

int c_derived = 0;

C++11

int modern{0};

What are the pros and cons of each method, if there are any? Why implement a new method? Does the compiler do anything different?

Upvotes: 3

Views: 1811

Answers (2)

Tristan Brindle
Tristan Brindle

Reputation: 16824

You're mistaken -- the int modern(0) form (with round brackets) was available in older versions of C++, and continues to be available in C++11.

In C++11, the new form uses curly brackets to provide uniform initialisation, so you say

int modern{0};

The main advantage of this new form is that it can be consistently used everywhere. It makes it clear that you're initialising a new object, rather than calling a function or, worse, declaring one.

It also provides syntactical consistency with C-style ("aggregate") struct initialisation, of the form

struct A
{
    int a; int b;
};

A a = { 1, 2 };

There are also more strict rules with regard to narrowing conversions of numeric types when the curly-bracket form is used.

Upvotes: 8

HaseebR7
HaseebR7

Reputation: 447

Using braces was just an attempt to introduce universal initialization in C++11.

Now you can use braces to initialize arrays,variables,strings,vectors.

Upvotes: 3

Related Questions