Destructor Destructor - 1 year ago 80
C++ Question

Initialize more than one non static data member of union

Consider following program which is ill formed according to standard

union Test {
int s{3};
float f;
Test() {}
Test(float f) : f(f) {} // this should be error

int main() {


C++11 standard N3376 clause 12 section 6.2.8 says that ( emphasis mine):

An attempt to initialize more than one non-static data member of a
union renders the program ill-formed.

But all the popular 3 compilers ( g++, clang++, MSVC++ ) compiles above program without producing any compiler error or warning. I think it is necessary for a compiler to give diagnosis in this program & program should fail in compilation.

See live demo tested on g++ here.

See live demo tested on clang++ here.

Are all the compilers broken here according to standard ? Is this compiler bug ?

Answer Source

The default constructor lets the s member be initialized, so only one member is initialized there.

The parameterized constructor only initializes the f member, so only one member is initialized there too.

Each constructor lets only one member be initialized, so the program is well-formed.

From §12.6.2/9 of N4594 (the upcoming C++17 standard):

In a non-delegating constructor, if a given potentially constructed subobject is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then

  • (9.1) — if the entity is a non-static data member that has a default member initializer (9.2) and either

    • (9.1.1) — the constructor’s class is a union (9.3), and no other variant member of that union is designated by a mem-initializer-id...

    [Unrelated text]

What the above quote basically says, is that brace-or-equal-initializer will only execute if there are no mem-initializer-id.

There is also language in the standard that says a union may only have a single brace-or-equal-initializer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download