Recently I am working on windows and I found that lot of data structures are defined as struct
with union
as member variables. Example of this would be
As a relic of the days when 64KB was quite a lot of memory, you have a facility in C++ that allows more than one variable to share the same memory (but, obviously, not at the same time). This is called a union, and there are four basic ways in which you can use one:
You can use it so that a variable A occupies a block of memory at one point in a program, which is later occupied by another variable B of a different type, because A is no longer required. I recommend that you don't do this. It's not worth the risk of error that is implicit in such an arrangement. You can achieve the same effect by allocating memory dynamically.
Alternatively, you could have a situation in a program where a large array of data is required, but you don't know in advance of execution what the data type will be -- it will be determined by the input data. I also recommend that you don't use unions in this case, since you can achieve the same result using a couple of pointers of different types and, again, allocating the memory dynamically.
A third possible use for a union is one that you may need now and again -- when you want to interpret the same data in two or more different ways. This could happen when you have a variable that is of type long, and you want to treat it as two values of type short. Windows will sometimes package two short values in a single parameter of type long passed to a function. Another instance arises when you want to treat a block of memory containing numeric data as a string of bytes, just to move it around.
You can use a union as a means of passing an object or a data value around where you don't know in advance what its type is going to be. The union can provide for storing any one of the possible range of types that you might have.
If you think I am a genius in explaining what a union is and some of it's possible applications, I can not take credit for this. (: This information came from Ivor Horton's Beginning Visual C++ 2010 which I happen to have sitting here on my desk. I hope this was helpful.