Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 255
Andrue Avatar asked Apr 25 '26 22:04

Andrue


2 Answers

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.

like image 146
Tristan Brindle Avatar answered Apr 27 '26 15:04

Tristan Brindle


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

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

like image 25
HaseebR7 Avatar answered Apr 27 '26 13:04

HaseebR7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!