[lug] Can't create union with classes that have copy CTOR's?

Tom Tromey tromey at redhat.com
Fri Mar 22 17:46:58 MST 2002


>>>>> "Viggy" == LittleViggy  <LittleViggy at alum.manhattan.edu> writes:

Viggy> I'm trying to create a union of 5 classes.  All five have copy
Viggy> constructors, and the compiler is erroring out.  Albeit, I'm
Viggy> using Microsoft (sorry), but there's nothing in their
Viggy> documentation that says this is specific to M$.

Viggy> Is this ANSI complient?  You can't create a union of classes
Viggy> with copy CTOR's?  If so, why not?

Suppose you have such a union and you do this:

    union foo x, y;
    initialize_foo (&y);
    x = y;

Which copy constructor should be invoked here?
This is a rhetorical question.  The compiler doesn't know which part
of the union is "active"; you might not either.

This is explained in Stroustrup, and probably other C++ books as well.

In general, don't trust compilers to tell you what is valid code.
Instead, read the standard.  Compilers might not respect the standard,
and you might have to modify your code to account for that -- but at
least you'll do it knowingly and you can mark it as unportable.  This
problem is particularly acute for C++.

Tom



More information about the LUG mailing list