Unions are very seldomly useful in C++. They're for conserving space if you have multiple different types of data in a single type... but are only going to use one type at a time.
Unions differ from structs because each member of a struct is stored independently and can retain its own value. IE:
1 2 3 4 5
|
struct foo
{
int a;
int b;
};
|
Here, 'a' and 'b' are two separate variables. Both can keep track of a value independently of another.
However that is not true of a union:
1 2 3 4 5
|
union foo
{
int a;
int b;
};
|
Here, 'a' and 'b'
[possibly] share memory space, and therefore you can only use one of them at a time. As soon as you write to 'a', the contents of 'b' become undefined. Likewise, writing to 'b' will invalidate/destroy any contents that are in 'a'.
The perk is that unions
[potentially] take up less memory, because they only need to reserve space for their largest member, whereas structs need to reserve space for the sum of all their members.
About the only time I've
ever seen unions be used effectively is in libs like SDL's event system. Where they have a struct for each kind of event:
1 2 3 4 5 6 7 8 9 10 11
|
struct SDL_Event
{
int type; // something to tell you what kind of event this is
union
{
SDL_KeyEvent key; // event data for keyboard
SDL_MouseEvent mouse; // event data for mouse
SDL_SizeEvent size; // event data for window resizing
// ... etc
};
};
|
This works because you only need one of those event types at a time. Which type you have depends on the 'type' variable.
However... SDL is a C lib. And in C++ there are much safer ways to approach this same problem using inheritance and other techniques.
So really... unions are not that useful in C++.