Does new[] call default constructor in C++?
Solution 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
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
.
flashnik
Updated on February 05, 2020Comments
-
flashnik over 4 years
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 resultarr
hascount
initialized objects of typeA
. 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 to0
.Why is there so different behavior? Does a default constructor not called only for built-in types?
-
James Curran over 13 years@rubber boots:
int i ();
does not initialize a varaible namedi
. It declares a functioni
returning an int. You may have meantint i = int();
-
fredoverflow over 13 years@James: In C++0x you can finally say what you mean:
int x{};
:) -
rubber boots over 13 years@James, oops - wtf did I write? Thanks for clearing this up. Wrong deduction from
int *i = new int();
. @Cerdic, Sorry for Posting BS. -
aardvarkk about 10 yearsWow, 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!