Search code examples
c++constructorconstantsunions

Constructor and anonymous union with const members


Is it possible to have an anonymous union with const members? I have the following:

struct Bar {
  union {
    struct { const int x, y; };
    const int xy[2];
  };
  Bar() : x(1), y(2) {}
};

With G++ 4.5 I get the error:

error: uninitialized member ‘Bar::<anonymous union>::xy’ with ‘const’ type ‘const int [2]’

Solution

  • This was a problem in GCC that was fixed in version 4.6. Your code now works fine.

    It still depends on a GCC extension because it uses an anonymous struct, but most compilers support them now. Also, the following code now builds properly with -pedantic:

    struct Bar {
      union {
        const int x;
        const int y;
      };
      Bar() : x(1) {}
    };
    

    That code is also accepted by Clang and Visual Studio 2010 (but fails with 2008).