♻️Union
In C++, a union is a special class type that allows you to store different data types in the same memory location. Here's a concise explanation of unions and their uses:
Definition: A union is a user-defined type where all members share the same memory location.
Key characteristics:
Only one member can hold a value at any given time.
The size of a union is determined by its largest member.
Main uses:
Memory optimisation: When you need to store different types of data, but never simultaneously, unions can save memory.
Type punning: Unions allow reinterpreting the same data as different types, though this can lead to undefined behaviour if not done carefully.
Interfacing with hardware: Unions are useful when working with low-level memory or hardware registers that can have multiple interpretations.
Last updated