I just read about unions in one of my C++ books. They give a brief explanation of what they do yet don''t give any examples of their uses in an application. I understand that they are several variables that share the same space in memory, but how would that work? A simple explanation on a beginner''s level would help a lot. Thanks
(1) You want something that can hold a value of more than one type (but just one at a time).
For example, there is a struct in Win32 called a VARIANT that contains a type field that is just some numeric identifier for a type followed by a union containing a long, float, void*, etc. It looks like there are actually about 40 different types that it can contain. If they declared each one individually, that would probably be something like 40 types * about 4 bytes per type = about 160 bytes per instance. With a union, it''s probably more like 8 bytes for the value.
These are typically used in places where this kind of flexible is needed such as variables in a scripting language (java-script for example) or keeping a list of properties (without wanting to know about the specific type when storing, loading ,etc.).
(2) You want to be able to access the same value in different ways.
For example, there is a struct in Windows Sockets called an in_addr that represents an IP address. These are 32-bit values that are typically displayed in a more human-friendly format as four groups of 8-bit values (127.0.0.1).
I''ve personally used unions for both reasons. Once I wanted to load in a list of properties from a saved file so I used a union as described in use 1. Another time, I needed to expand a member of struct from one to an array of four but I couldn''t do so in a way that broke existing code. My solution was to create a union that contained the original declaration along with the array -- the original name now referred to the 0th element of the array. Best of both worlds!