1

When I declare a an array, all the variables/objects get declared. But what happens with the objects, if their class has constructors? The class I'm using has 2 constructors - one with no arguments and one with a few arguments. Will the first constructor activate after the declaration? Or no constructors will activate?

If the first case happens, I'll have to make a function that replaces the constructors.

So, what happens with the objects in a newly declared array?

2 Answers 2

8

It depends how you declare the array. The members will be either default, value, or copy-initialized:

Foo x[] = { Foo(1), Foo(true, 'a'), Foo() };  // copy-initialize
Foo x[3] = { };                               // value-initialize
Foo x[3];                                     // default-initialize

For class types, default- and value-initialization call the default constructor. Copy-initialization may call the appropriate constructor directly.

If you don't want to use the default-constructor, you won't get arround the brace-initializer and spelling out each member.

Sign up to request clarification or add additional context in comments.

3 Comments

You mean Foo x[] = { new Foo(1), ...} ?
@ThanhNguyen: that would require a Foo(Foo *) constructor and would induce a memory leak if that constructor doesn't delete its argument (which would be very bad style).
@ThanhNguyen: No, I mean Foo x[] = { Foo(1) };. I could also say Foo x[] = { 1 };, but that's a bit different -- it requires a one-argument constructor, and also an implicit copy constructor. C++11 makes this a bit more flexible by also allowing Foo x[] = { {true, 'a'} };, though again we need an accessible implicit copy constructor.
2

Arrays will invoke the default constructors on all objects if the underlying type has a non-trivial default constructor.

I don't remember the rules exactly, but ints, char*s, structs whose members all have trivial constructors, etc., all have trivial default constructors. Arrays of these things (and arrays of arrays of these things, etc.) won't be initialised unless you do so explicitly.

An explicitly declared default constructor is never trivial, so the Foo objects in your array will be default-constructed.

3 Comments

I think you're referring to default-initialization of fundamental types in the last paragraph, which indeed leaves the variables uninitialized.
@KerrekSB: No, not just fundamental types. Structs, unions, structs of arrays of structs, etc., can all have trivial default constructors.
Yes, indeed, this applies recursively to structs and arrays of those things!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.