Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 351
flashnik Avatar asked Aug 26 '10 13:08

flashnik


People also ask

Who calls the default constructor?

It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.

Is default constructor called automatically?

If no constructors are explicitly declared in the class, a default constructor is provided automatically by the compiler.

Why is it called a default constructor?

This constructor is called the default constructor because it is run "by default;" if there is no initializer, then this constructor is used. The default constructor is used regardless of where a variable is defined.

When should a default constructor be removed?

Deleting the default constructor of a class is a good idea when there are multiple choices for the default or uninitialised state. For example, suppose I have a class, template<typename F> class Polynomial; which represents a polynomial over a field, F .


2 Answers

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](); 
like image 121
sharptooth Avatar answered Sep 19 '22 01:09

sharptooth


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.

like image 25
Cedric H. Avatar answered Sep 21 '22 01:09

Cedric H.