![]() |
VOOZH | about |
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.
Sizeof A: 4 Sizeof B: 40
The above union's memory can be visualized as shown:
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;
21 5.2 N
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 Name1union name2 {
// Data members of Name2} inner;
};
Accessing members of union using dot(.) operator:
name1 obj;
obj.inner.member;
Example:
Employee ID: 101 Hourly Rate: Rs 300 Salary: Rs 50000
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.
Employee ID: 101 Hourly Rate: Rs 300 Salary: Rs 50000