Unions

Get introduced to the concept of unions.

We'll cover the following

Introduction

Unions, a low-level feature inherited from the C programming language, allow more than one member of the user-defined type to share the same memory area. Unions are very similar to structs with the following main differences:

  • Unions are defined by the union keyword.

  • The members of a union are not independent; they share the same memory area.

Just like structs, unions can have member functions. The examples below will produce different results depending on whether they are compiled on a 32-bit or a 64-bit environment.
Naturally, struct objects are as large as necessary to accommodate all of their members:

Get hands-on with 1400+ tech skills courses.