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);
...
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.
When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated.
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.
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)};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With