44

When I use new[] to create an array of my classes:

int count = 10;
A *arr = new A[count];

I see that it calls a default constructor of A count times. As a result arr has count initialized objects of type A. But if I use the same thing to construct an int array:

int *arr2 = new int[count];

it is not initialized. All values are something like -842150451 though default constructor of int assignes its value to 0.

Why is there so different behavior? Does a default constructor not called only for built-in types?

flashnik
  • 1,900
  • 4
  • 19
  • 38
  • Possible duplicate of [How can I make \`new\[\]\` default-initialize the array of primitive types?](https://stackoverflow.com/questions/2468203/how-can-i-make-new-default-initialize-the-array-of-primitive-types) – Suma Feb 04 '18 at 18:19

4 Answers4

73

See the accepted answer to a very similar question. When you use new[] each element is initialized by the default constructor except when the type is a built-in type. Built-in types are left unitialized by default.

To have built-in type array default-initialized use

new int[size]();
Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 26
    Wow, I didn't actually know you could add the braces to default initialize built-in types. I've been working with C++ for years. That's either exciting or very sad! – aardvarkk Apr 25 '14 at 14:09
4

Built-in types don't have a default constructor even though they can in some cases receive a default value.

But in your case, new just allocates enough space in memory to store count int objects, ie. it allocates sizeof<int>*count.

Suma
  • 33,181
  • 16
  • 123
  • 191
Cedric H.
  • 7,980
  • 10
  • 55
  • 82
  • 3
    @rubber boots: `int i ();` does not initialize a varaible named `i`. It declares a function `i` returning an int. You may have meant `int i = int();` – James Curran Aug 26 '10 at 14:33
  • 1
    @James: In C++0x you can finally say what you mean: `int x{};` :) – fredoverflow Aug 26 '10 at 14:39
  • 1
    @James, oops - wtf did I write? Thanks for clearing this up. Wrong deduction from `int *i = new int();`. @Cerdic, Sorry for Posting BS. – rubber boots Aug 26 '10 at 19:38
2

Primitive type default initialization could be done by below forms:

    int* x = new int[5];          // gv gv gv gv gv (gv - garbage value)
    int* x = new int[5]();        // 0  0  0  0  0 
    int* x = new int[5]{};        // 0  0  0  0  0  (Modern C++)
    int* x = new int[5]{1,2,3};   // 1  2  3  0  0  (Modern C++)
SridharKritha
  • 8,481
  • 2
  • 52
  • 43
0

int is not a class, it's a built in data type, therefore no constructor is called for it.

Hamid Nazari
  • 3,905
  • 2
  • 28
  • 31