VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-unions/

⇱ C++ Unions - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Unions

Last Updated : 26 Apr, 2026

In C++, a union is a user-defined data type that can hold members of different data types. The size of a union is at least the size of its largest member, but it may be larger due to alignment requirements. All members share the same memory space, so only one member can store a valid value at a time.

  • Unlike structures, all members of a union are stored in the same memory location.
  • Since all members share the same memory, changing the value of one member overwrites the value of the others.

Output
Sizeof A: 4
Sizeof B: 40

The above union's memory can be visualized as shown:

Union Declaration

A union is declared similarly to a structure. Provide the name of the union and define its member variables:

union union_Name {
type1 member1;
type2 member2;
..
};

After declaring a union, a variable can be created as follows:

union_name variable_name;

We can also declare a variable at the declaration of union.

union union_Name {
type1 member1;
type2 member2;
.
.
}variable_name;


Output
21
5.2
N

Nested Union

A union can be defined within a structure, class or another union, known as a nested union. This approach helps efficiently organize and access related data while sharing memory among the union’s members.

Syntax:

union name1 {
// Data members of Name1

union name2 {
// Data members of Name2

} inner;
};

Accessing members of union using dot(.) operator:

name1 obj;
obj.inner.member;

Example:


Output
Employee ID: 101
Hourly Rate: Rs 300
Salary: Rs 50000

Anonymous Unions

An anonymous union is a union without a name whose members can be accessed directly and behave like members of the outer structure or union.


Output
Employee ID: 101
Hourly Rate: Rs 300
Salary: Rs 50000

Applications of Union in C++

  • Used for memory efficiency, especially in embedded systems
  • Allows different data types to share the same memory, reducing footprint
  • Can map hardware registers with multiple interpretations
  • Suitable for data that takes one of several types, but never simultaneously
Comment
Article Tags: