On Wed, Nov 12, 2008 at 12:53:54PM +1000, Mark Tall wrote:
> Hello,
> 
> I've come across an oddity in C++, involving anonymous unions and
> const variables. Neither of the two classes below will compile using
> gcc 4.3.0.  Is this a bug in gcc or the C++ standard itself ?
> 
> class my_class_1
>   {
>   union
>     {
>     const int x;
>     const int y;
>     };
> 
>   my_class_1() : x(0), y(0) {}
>   };

The same memory is being initialized in two potentially conflicting ways.
Consider for example

 class my_class_1
   {
   union
     {
     const int x;
     const int y;
     };
 
   my_class_1() : x(0), y(1) {}

Here you'd be directing the compiler to store a zero and a one in
the same memory.

> class my_class_2
>   {
>   union
>     {
>     const int x;
>     const int y;
>     };
> 
>   my_class_2() : x(0) {}
>   };
> 
> 
> compiler output:
> 
> my_class.cpp: In constructor 'my_class_1::my_class_1()':
> my_class.cpp:10: error: initializations for multiple members of
> 'my_class_1::<anonymous union>'
> my_class.cpp: In constructor 'my_class_2::my_class_2()':
> my_class.cpp:22: error: uninitialized member 'my_class_2::<anonymous
> union>::y' with 'const' type 'const int'

Here you have the problem that a const member must have an initializer,
yet you cannot initialize both x and y.

I think it could be argued that unions shouldn't have const members,
and it would be a good idea for the standard to ban them.

Reply via email to