MyClass mc2[] = { MyClass(), MyClass() }; //this calls the constructor twice
MyClass mc1[4]; // this calls the constructor 4 times. Why?
So, my question is: why does a declaration of an array of object with no initialization cause the default constructor to be called?
In C++, an array of MyClass
of size 4, is four actual objects. It is somewhat like a struct containing four members of that type, although of course you access the members using different syntax and there are other technical differences.
So, defining that array results in the 4 objects being constructed for the same reason (and under approximately the same circumstances) as defining one object of that type causes that one to be constructed.
Contrast this state of affairs with another programming language: in Java an array of MyClass
of size 4 is just four pointers, which are permitted to be null. So creating it doesn't create any MyClass
objects.
So, my question is: why does a declaration of an array of object with no initialization cause the default constructor to be called?
Because that's how C++ works.
A MyClass mc1[4]
is almost as if you had created four different MyClass
objects:
MyClass mc1_1;
MyClass mc1_2;
MyClass mc1_3;
MyClass mc1_4;
In a class with a default constructor, this quite naturally implies that the default constructor is used to initialise each object.
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