1

When I declare a structure instance is it initialized or do I have to make a constructor?

How much will the constructor affect the performance since I need an array of 1000 structures?

The structure I need is very simple and it contains 4 integers. I need them to be initialized to 0.

This is my code:

struct MyStruct { int a; int b; int c; int d; MyStruct() : a(0), b(0), c(0), d(0) {} }; int main() { MyStruct array[1000]; } 
3
  • If you take away the constructor (and thus make it implicit) you can do MyStruct array[1000]() which will zero-initialize all the integers. Commented Feb 2, 2015 at 16:26
  • 1
    @0x499602D2 declaration of 'array' as array of functions Are you sure that's correct syntax? Commented Feb 2, 2015 at 16:32
  • @user2079303 Right, my mistake. It should be MyStruct array[1000]{} (which only works >=C++11) Commented Feb 4, 2015 at 20:14

1 Answer 1

1

You are declaring a variable in main, but only as a side-effect of defining it.

And all objects are default-initialized, unless you ask for something else.

Still, that's not quite as much as you might thing. A default-initialized basic type, which is neither in static nor in thread-local storage, is still indeterminate after that.

But never fear, your type has a user-defined default-ctor, so default-initialization means that is called.
And as that value-initializes all members, everything is initialized.

If it was an aggregate, this would zero-initialize it:

MyStruct array[1000] = {}; 

Regarding performance, there's nothing to be done but measuring, and asking the compiler to optimize it. Keep in mind that the fastest code is code that isn't there.

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

1 Comment

Or just MyStruct array[1000]{}; to conserve the limited supply of characters.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.