Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why use an initializer list when it initializes nothing?

In this snippet:

struct Result
{
    Result() : output1(){};
    int output1[100];
}

What does Result() : output1(){}; do?

I know that : output1() is the initializer list, but why even mention it when it does nothing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It does something: It zero-initializes output1 instead of leaving it uninitialized.

To elaborate, this is called value initialization and is explained in detail here: https://en.cppreference.com/w/cpp/language/value_initialization

The effects of value initialization are:

  1. if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
  2. if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
  3. if T is an array type, each element of the array is value-initialized;
  4. otherwise, the object is zero-initialized.

Since it is an array, case 3 applies. Then the rule applies recursively for each value in the array, leading to case 4 which sets the value to 0.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading