How to use Unions in C++ ?
Save memory space!
What is a Union?
union is similar to a
struct, the difference is that Union reuses the space for the next type given inside it, whereas Struct adds it to a new block.
Declaration of a Union:
It is also similar to classes, but apart from the reuse difference, like Structs, Union doesn’t need
public to access data, in classes if you don’t inform it will be
private by default.
Let’s suppose you have this code that stores data for a certain product:
If you compile the code above, notice that the output will be just the
id we assigned:
But now let’s also assign data to the
value and print:
Note that the
value output was correct, but the
id turned into a strange number.
Also note that if you use this same code with
struct this will not happen, for example:
As I said,
union reuses the space, that is, the
int (4 bytes) is smaller than the
double (8 bytes), so that reused space becomes a Memory Garbage .
Let’s illustrate for didactic purposes only:
int space is reused and it writes the
struct it keeps that
int space and creates a new one for the
If you reverse the definition orders this will not happen because
int is smaller than
Unions were created precisely to save memory space, but programmers have gotten a writing addiction and more commonly use Structs.
However, in code from some programmers who care a lot about optimization you will find more Unions than Structs .