Search code examples
c++referenceaggregate-initialization

Is this aggregate initialization or reference-initialization (revisted)?


This is a follow up question to Is this reference-initialization or aggregate-initialization?

Consider the same example:

struct A {};
struct B : A{};

A a{ B() };

Does this is an aggregate initialization or reference initialization?

I mean by "reference-initialization" that the implicity-declared copy constructor A::A(const A&) is used where the reference parameter is bound to A subobject of the initializer expression B().

Also why this is not an aggregate initialization even though the class A is an aggregate class?


Solution

  • Does this is an aggregate initialization or reference initialization?

    A is an aggregate and A a{ B() } is list initialization according to the following rule(s):

    The effects of list-list-initialization of an object of type T are:

    • If T is an aggregate class and the braced-init-list has a single element of the same or derived type (possibly cv-qualified), the object is initialized from that element (by copy-initialization for copy-list-initialization, or by direct-initialization for direct-list-initialization).

    • Otherwise, if T is a character array and the braced-init-list has a single element that is an appropriately-typed string literal, the array is initialized from the string literal as usual.

    • Otherwise, if T is an aggregate type, aggregate initialization is performed.

    (emphasis mine)

    Note in the above, we do not reach bullet 3 as bullet 1 is satisfied and so used.

    This means that the object A is initialized from the single element B() using direct-initialization. This in turn means that the copy constructor A::A(const A&) will be used.

    Here, the parameter const A& of the copy ctor A::A(const A&) can be bound to a B object so this works without any problem.


    why this is not an aggregate initialization even though the class A is an aggregate class?

    Because to do aggregate initialization bullet 3 here should be reached and satisfied but we never reach bullet 3 because bullet 1 is satisfied.