Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++: why does a constructor get called when an array of objects is declared?

Tags:

c++

arrays

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?

like image 781
Matryo Avatar asked Nov 15 '15 13:11

Matryo


Video Answer


2 Answers

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.

like image 131
Steve Jessop Avatar answered Nov 01 '22 19:11

Steve Jessop


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.

like image 45
Christian Hackl Avatar answered Nov 01 '22 20:11

Christian Hackl