'Does new[] call default constructor in C++?
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?
Solution 1:[1]
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]();
Solution 2:[2]
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.
Solution 3:[3]
int is not a class, it's a built in data type, therefore no constructor is called for it.
Solution 4:[4]
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++)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Suma |
| Solution 3 | Hamid Nazari |
| Solution 4 | SridharKritha |
