- A union is a data structure that allows you
to use the same memory space for different types.
For example, here I have union.cpp
from chapter three of the exercise files,
And if you're familiar with IPv4 addresses,
it's a 32 bit number that's typically displayed as octets.
And so here we have this union, which
has both the 32 bit integer
and four, eight bit octets
And they're called octets because they're eight bits.
And so, I can initialize my address
as octets here. And when I build and run this,
you see I can display it both ways.
I can display it both as the normal dot separated octets
you normally see for an IP address,
or as this 32 bit integer in hexadecimal,
and all using the same data space.
So my octets, A, B, C, and D
So there's my structure of octets, ABC and D,
using the same memory space as a 32 bit integer.
So unions may be used to conserve space and data structures,
reusing space for various purposes
that are not needed in the same context,
or they're sometimes used for crude polymorphism like this.
Where you have two different representations
of the same data, you need to be careful about
type checking. Union might be a convenient solution
for some simple cases like this IPv4 address.
For more complex uses,
you may consider using a class.