In C ++: why is the constructor called when declaring an array of objects?

MyClass mc2[] = { MyClass(), MyClass() }; //this calls the constructor twice MyClass mc1[4]; // this calls the constructor 4 times. Why? 

So my question is: why declaring an array of an object without initialization calls the default constructor?

+5
source share
2 answers

In C ++, a MyClass size 4 array is four actual objects. This is similar to a four-member structure of this type, although of course you gain access to members using a different syntax and there are other technical differences.

So, the definition of this array leads to the construction of 4 objects for the same reason (and under approximately the same circumstances) that define one object of this type, makes it build.

Compare this state of affairs with another programming language: in Java, a MyClass array of size 4 is just four pointers that are allowed to be null. Therefore, creating it does not create any MyClass objects.

+8
source

So my question is: why declaring an array of an object with no initialization does not call the default constructor?

So how does C ++ work.

A MyClass mc1[4] almost as if you created four different MyClass objects:

 MyClass mc1_1; MyClass mc1_2; MyClass mc1_3; MyClass mc1_4; 

In a class with a standard constructor, this naturally means that the default constructor is used to initialize each object.

+5
source

Source: https://habr.com/ru/post/1235992/


All Articles