Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does C++ not allow `new` to call constructor when creating arrays

Lets say you are creating an array of objectes on the heap like so:

myClass * objectPtr = new myClass[10];

new only invokes the default constructor, and (based on my readings) does not allow any other constructor to be invoked.

Is there any logic behind why new cannot invoke any other constructor? It would seem better to do something like

myClass * objectPtr = new myClass[10](12);

as opposed to

myClass * objectPtr = new myClass[10];
objectPtr[0] = myClass(12);
objectPtr[1] = myClass(12);
...
like image 271
1110101001 Avatar asked Jun 10 '14 20:06

1110101001


People also ask

Do arrays call new constructors?

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.

Does new call the constructor?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.

How many times constructor is called for an array?

The constructor and destructor are called once for each item in the array, while new[] is only called once because you're only creating one array.


1 Answers

Why does C++ not allow new to call constructor when creating arrays

It does. It is just a bit tedious:

struct my_class
{
    my_class() {}
    my_class(int, int) {}   
};

int main() 
{
  my_class* objectPtr = new my_class[3]{my_class(1,2),
                                        my_class(), 
                                        my_class(3,4)};
}
like image 53
juanchopanza Avatar answered Oct 03 '22 17:10

juanchopanza