Must aggregate field constructor be public to use aggregate initialization in C++?

  aggregate-initialization, c++, c++20

Please consider the code with aggregate struct B having a field of class A with a private constructor:

class A { A(int){} friend struct B; };
struct B { A a{1}; };

int main()
{
    B b; //ok everywhere, not aggregate initialization
    //[[maybe_unused]] B x{1}; //error everywhere
    [[maybe_unused]] B y{}; //ok in GCC and Clang, error in MSVC
}

My question is about aggregate initialization of B. Since the initialization takes place on behalf of the calling code (main function here), I expected that it must be denied by the compiler, since A‘s constructor is private. And indeed the construction B{1} fails in all compilers.

But to my surprise the construction B{} is accepted by both GCC and Clang, demo: https://gcc.godbolt.org/z/7851esv6Y

And only MSVC rejects it with the error error C2248: 'A::A': cannot access private member declared in class 'A'.

Is it a bug in GCC and Clang, or the standard permits them to accept this code?

Source: Windows Questions C++

LEAVE A COMMENT