On Wed, Nov 07, 2007 at 05:22:01AM +1100, skaller wrote: > > One way to do this in C++ is to derive the different representations that > > might appear in your "union" from a common base class, and use placement > > new to lay them out. > > I don't understand. You cannot put ANY constructable types > in a union.
That's why I said "union", with the quotes. We're not talking about a union keyword, we're talking about how to get the effect you want, legally, as opposed to the illegal way that you are doing it. If you have a pointer or reference to Base, the object might really be any class derived from Base. With placement new, you make a buffer big enough to hold the object, you can then construct an object of the right type there. This kind of code could be auto-generated by your compiler and would be quick and type-safe. The actual type of the storage is an array of char, which by the rules of the language may alias to any type. But this is off-topic.