What is the difference between union and struct in C++?
In C++, both union and struct are keywords used to define custom data types.
- Structural organization:
- struct is used to define a data structure containing members of different data types.
- Each member of the struct occupies its own independent memory space.
- The members within a struct can coexist and their memory addresses are contiguous.
- Structures can have member functions that can manipulate the data within the structure.
- union: a collective body
- The union is also used to define a data structure that contains members of different data types.
- All members in the union share the same memory space.
- Only one member of the union can exist and be used at a time.
- The size of the union is determined by its largest member.
- Unions cannot have function members.
Therefore, structs are suitable for situations where different types of data need to be stored simultaneously, with each member occupying separate memory space; while unions are suitable for situations where memory space needs to be saved, with different members sharing the same block of memory.