1

I know the difference between new int() and new int(10). In first case 0 is assigned and in second case 10 is assigned to newly created int. But what is the between new int {}. We use {} for array initialization like new a[]{4,5,6}. But for single variable what is the meaning of using braces while initializing?

/* Combined usage and initialized to 0*/
    int *ptr2 = new int();
    cout<<"*ptr2 = "<<*ptr2<<endl;

    /* Allocated memory can be initialized to specific value */
    int*ptr3 = new int(5);
    cout<<"*ptr3 = "<<*ptr3<<endl;

    int* ptr5 = new int{500};
    cout<<"*ptr5 = "<<*ptr5<<endl;
Farhad
  • 4,119
  • 8
  • 43
  • 66
Rajesh
  • 1,085
  • 1
  • 12
  • 25
  • 4
    Possible duplicate of [Initialization difference with or without Curly braces in C++11](https://stackoverflow.com/questions/21150067/initialization-difference-with-or-without-curly-braces-in-c11) – Tas Oct 09 '17 at 05:06
  • Or maybe https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives – Tas Oct 09 '17 at 05:07

2 Answers2

3

Your output is this:

*ptr2 =  0 

*ptr3 =  5 

*ptr5 =  500 

No difference in your situation.

But in general :

( expression-list )     (1)     
= expression            (2)     
{ initializer-list }    (3) 

1) comma-separated list of arbitrary expressions and braced-init-lists in parentheses

2) the equals sign followed by an expression

3) braced-init-list: possibly empty, comma-separated list of expressions and other braced-init-lists

Reference: http://en.cppreference.com/w/cpp/language/initialization

Farhad
  • 4,119
  • 8
  • 43
  • 66
1

In the particular case of int (or any integral type e.g. long) there is no difference between new int(10) and new int{10}.

Read more about variable initialization.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547