Matryo
Matryo

Reputation: 59

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

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?

Upvotes: 5

Views: 254

Answers (2)

Christian Hackl
Christian Hackl

Reputation: 27538

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.

Upvotes: 5

Steve Jessop
Steve Jessop

Reputation: 279315

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.

Upvotes: 8

Related Questions