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

Aggregate Initialization when initialization values is fewer than the number of members

As per the document, which states that[emphasise mine]:

Missing initializers in an initializer list

If an aggregate is initialized but the number of initialization values
is fewer than the number of members, then all remaining members are
initialized with an empty initializer list. In most cases, this will
perform value-initialization on those members.

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

How to understand that in the right way? How remaining members are initialized with an empty initializer list?

The document says this will perform value-initialization on those members in most cases. When is not that case?

Maybe it’s easier to understand with a simple example code:

#include <iostream>

struct S {
  int a;
  int b;
};

int main() {
  S s = { 0 }; 
  S s1{ 0 }; 
  //the output will be always zeros?
  std::cout<<"s.a = " <<s.a <<", s.b = " <<s.b<<std::endl;
  std::cout<<"s1.a = "<<s1.a<<", s1.b = "<<s1.b<<std::endl; 
}

>Solution :

How remaining members are initialized with an empty initializer list?

The same way as A a = {};.

This member initialization is not equivalent to value-initialization when (and only when) the member is of a class type that does not have a default constructor, but has an initializer-list constructor.

struct A {
    A(std::initializer_list<int>) {}  // #1
};

A a = {};  // calls #1

struct B {
    int x;
    A a;
};

B b = {42};  // b.a is initialized by calling #1
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