Unions in C++

In a C++ programming language, the union is a special user-defined data type that allows to the storage of different data types in the same memory location.

“union”  uses the same memory location for multiple-purpose.

 Or

In a union data type, a single variable, i.e., the same memory location, can be used to store multiple types of data.

In a C++ programming union is similar to the structure but the major difference is that it requires less memory than structure.

Apart from this difference, you can define a union with many variables, but only one member can contain single value at any given time.

Defining Unions in C++

We can define a union with the “union” keyword. “union” defines a new user-defined data type with one or more than one members.

Syntax of union definition:

  In the union’s definition at the end & before the final semicolon, you can specify one or more union variables but it is optional.

When a union object is created, memory is allocated for the largest member of the union.

Changing the value of one member of the union will overwrite the values of all other members. It is the programmer’s responsibility to keep track of which member is currently in use.

Example:

Above define a union type named book having three members i, f, and c.

In the above example, the variables of Book is book1 and book2. These variables can store an integer, a floating-point number, or a string of characters.

During the union definition, memory occupied by a union variable will be large enough to hold the largest member of the union.

In the above example, user-defined data type Book will occupy 30 bytes of memory space because this is the maximum space that can be occupied by a character string. 

Example: Write a program to store and print the following information such as name, roll number, class and section of the student using union.

Output

In the above example, we can see that the values of name, rollno, and Class of union got corrupted because the final value assigned to the variable has occupied the memory location and this is the reason that the value of Section is getting printed very well.

Note: In a union, one variable can contain a single value at any given time which is the main purpose of having unions −

Correct Implementation of Above program

Output

Difference between structure and union

Lets see student structure

Output

Here we discussed Unions in C++.

C++ Program For Student Details Using Array Of Objects

Categories C++