If I have a class:
class Odp
{
int i;
int b;
union
{
long f;
struct
{
WCHAR* pwszFoo;
HRESULT hr;
};
};
}
Union means that, of all values listed, it can only take on one of those values at a time? How does that work in terms of accessing these variables? How would I access hr directly? If I set hr, what happens if I try to access f?
This is a very fraught area in the C++ standard – basically a union instance, per the standard can only be treated at any one time as if it contained one “active” member – the last one written to it. So:
then:
is OK, but:
is not. However, there are vast volumes of existing code that say that both are OK. and in neither, or any, case will an exception be thrown for an “invalid” access. The C++ language uses exceptions exceptionally (!) sparingly.
Basically, if you find yourself using unions in your C++ code to deal with anything but C libraries, something is wrong.