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

C++ aggregate initialization

According to the C++ reference, aggregate initialization has the following syntax:

T object = { arg1, arg2, ... }; 
T object { arg1, arg2, ... };
T object = { .des1 = arg1 , .des2 { arg2 } ... };   
T object {.des1 = arg1 , .des2 { arg2 } ... };

So this would be an example of aggregate initialization:

int a, b;
std::size_t arr[]{a,b};

But if an aggregate is a member of a class initialized in the member initializer list, is it still an aggregate initialization or a different type of initialization?

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

struct S
{
    template <typename T>
    S(T a, T b)
        : arr{ a, b }
    {   }

    std::size_t arr[2];
};

Update:
I thought the question is clear, but having read the comments, I realize that I have to clarify that it is about the array member arr, not about S.

>Solution :

Aggregate initialization refers to a certain semantic of initialization, not to a syntactical form of initialization.

The syntax listed by cppreference just demonstrates the possible syntactical forms that may result in aggregate initialization, but they aren’t generally aggregate initialization.

The syntactical forms are called list initialization instead. List initialization may only result in aggregate initialization if the object type is an aggregate type. But for aggregate types, with few exceptions, list initialization does result in aggregate initialization.

In the this case S::arr is an array type and so an aggregate type. Consequently arr{ a, b } in the constructor’s initializer list is aggregate initialization of arr as well.

The form of initialization is determined only be the initializer part of the syntax, i.e. { a, b }. The context in which the initializer appears, such as a variable declaration or constructor initializer list, doesn’t matter.

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