Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate an Object with curly braces C++

I've read numerous explanations on initializing with braces:

PhoneNumber homePhone = {858, 555, 1234};

as well as

int x2 = val; // if val==7.9, x2 becomes 7 (bad)

char c2 = val2; // if val2==1025, c2 becomes 1 (bad)

int x3 {val}; // error: possible truncation (good)

char c3 {val2}; // error: possible narrowing (good)

char c4 {24}; // OK: 24 can be represented exactly as a char (good)

char c5 {264}; // error (assuming 8-bit chars): 264 cannot be 
               // represented as a char (good)

However, I've come across a bit of code here that I can't find an example on, perhaps I do not know the term so that I can google it:

auto ac1 = ArrayClass{};

I am used to doing

ArrayClass ac1 = new ArrayClass();

First of all is:

auto ac1 = ArrayClass{};

the same as

ArrayClass ac1 = ArrayClass{};

Secondly,

Am I only allowed to use braces if I used an initialization list in my constructor?

And lastly, if I have parameters, is the following correct?

auto ac1 = ArrayClass{1,4,"hi", true}

Thank you for your help

like image 903
UnseededAndroid Avatar asked Oct 06 '16 04:10

UnseededAndroid


2 Answers

This style of initialization is called list-initialization. You can read more on it at http://en.cppreference.com/w/cpp/language/list_initialization.


I am used to doing

ArrayClass ac1 = new ArrayClass();

That is not correct C++ syntax. You can use:

 ArrayClass* acPtr = new ArrayClass();

First of all is:

auto ac1 = ArrayClass{};

the same as

ArrayClass ac1 = ArrayClass{};

Yes, it is same.


Secondly,

Am I only allowed to use braces if I used an initialization list in my constructor?

Yes.


And lastly, if I have parameters, is the following correct?

auto ac1 = ArrayClass{1,4,"hi", true};

You can use that syntax if:

ArrayClass has at least four members, and
the first member can be initialized using 1, and
the second member can be initialized using 4, and
the third member can be initialized using "hi", and
the fourth member can be initialized using true, and
any other remaining members can be value initialized.

You can read more about value-initialization at http://en.cppreference.com/w/cpp/language/value_initialization.

like image 199
R Sahu Avatar answered Sep 30 '22 10:09

R Sahu


auto ac1 = ArrayClass{};

allocates on the stack and the variable is automatically cleaned up when the stack goes away.

ArrayClass ac1 = new ArrayClass();

is invalid unless ArrayClass is typedef'd to be a pointer. Regardless, new ArrayClass() allocates memory on the heap that must be explicitly cleaned up by calling delete on it.

auto ac1 = ArrayClass{};

the same as

ArrayClass ac1 = ArrayClass{};

yes.

like image 32
xaxxon Avatar answered Sep 30 '22 10:09

xaxxon