Ayrosa Ayrosa - 20 days ago 6
C++ Question

Where in the Standard does it say that the default member initializer for U::j should be ignored by the compiler?

Consider the following snippet:

#include <iostream>
union U{
U(): i(1) {}
int i;
int j = 2; // this default member initializer is ignored by the compiler
};

U u;

int main(){
std::cout << u.i << '\n';
std::cout << u.j << '\n';
}


The code prints (see live example):

1
1


Where in the Standard does it say that the default member initializer for the member
U::j
is ignored by the compiler?

Note that the union below doesn't compile and this is OK according to [class.union.anon]/4. I was thus expecting the snippet above also not to compile.

See live example:

union U{
int i = 1;
int j = 2;
};

Answer

Where in the Standard does it say that the default member initializer for the member U::j is ignored by the compiler?

See [class.base.init] paragraph 9 bullet 9.1 in the C++17 CD.

N.B. your demo has undefined behaviour, because the active member of the union is i but you read from j. This works with some compilers as a non-standard extension, but is not allowed in ISO C++.