In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory separately for each member variable. The size of the union is equal to the size of the largest data type.
Memory space can be used by one member variable at one point in time, which means if we assign value to one member variable, it will automatically deallocate the other member variable stored in the memory which will lead to loss of data.
Need of Union in C++
- When the available memory is limited, it can be used to achieve memory efficiency.
- It is used to encapsulate different types of data members.
- It helps in optimizing the performance of applications.
Syntax of Union in C++
Union is defined using the ‘union’ keyword.
union Union_Name {
// Declaration of data members
}; union_variables;
After defining the union we can also create an instance of it the same as we create an object of the class or declare any other data type.
int main(){
union Union_Name var1;
// or
Union_Name var1;
}
Example of Union in C++
C++
#include <iostream>
using namespace std;
union geek {
int age;
char grade;
float GPA;
};
int main()
{
union geek student1;
student1.age = 25;
cout << "Age : " << student1.age << endl;
student1.grade = 'B';
cout << "Grade : " << student1.grade << endl;
student1.GPA = 4.5;
cout << "GPA : " << student1.GPA << endl;
return 0;
}
|
Output
Age : 25
Grade : B
GPA : 4.5
We have not assigned the values to all data members in one go as we do normally because they share the same memory location and if we do so then their value will be overwritten.
C++ Program to Illustrate that Data Members of Union Share Same Memory Location
In the below example, we are verifying that is it actually data members of the union are sharing the same memory or not.
C++
#include <iostream>
using namespace std;
union geek {
int age;
float GPA;
double marks;
};
int main()
{
geek student1;
cout << "Memory address of age: " << &student1.age;
<< endl;
cout << "Memory address of GPA: " << &student1.GPA;
<< endl;
cout << "Memory address of marks: " << &student1.marks;
<< endl;
cout << "Size of a union: " << sizeof(student1) << endl;
return 0;
}
|
Output
Memory address of age: 0x7ffcfc68fc20
Memory address of GPA: 0x7ffcfc68fc20
Memory address of marks: 0x7ffcfc68fc20
Size of a union: 8
Explanation
First, we have defined a union and defined three different data members inside it. After that, in the main function, we have defined a union variable. Now, we have printed the address of all data members of the union using the reference operator ‘&’.
We can see in the output that the addresses of all three data members are the same which proves that members of the union shared the same memory. We have also printed the size of a union which is ‘8’ because double takes 8 bytes and it largest among int, float, and double.
Anonymous Unions in C++
Just like anonymous objects we also have anonymous unions in C++ that are declared without any name inside a main function. As we do not define any union variable we can directly access the data members of the union that is why their data members must be declared with unique names to avoid ambiguity in the current scope.
Syntax
union {
// Declaration of data members
}; union_variables;
Example
In the main function, we have defined an anonymous without defining any variable. After that, we assigned value to data members of a union and print them.
C++
#include <iostream>
using namespace std;
int main() {
union {
int standard;
char section;
};
standard = 8;
cout<<"Standard = "<<standard<<endl;
section = 'A';
cout<<"Section = "<<section<<endl;
return 0;
}
|
Output
Standard = 8
Section = A
Union-like Classes in C++
A union-like class is just a class with at least one anonymous union defined inside it and the data members defined in an anonymous union are known as variant members.
Example: C++ program to illustrate Union-like classes
C++
#include <iostream>
#include <string>
using namespace std;
class student {
public:
string name;
union {
int standard;
char section;
};
};
int main()
{
student s1;
s1.name = "geek";
cout << "Name : " << s1.name << endl;
s1.standard = 9;
cout << "Standard : " << s1.standard << endl;
s1.section = 'D';
cout << "Section : " << s1.section << endl;
return 0;
}
|
Output
Name : geek
Standard : 9
Section : D
Explanation
In the above example, we have created a class ‘student’ a data member, and an anonymous union inside it which is called a union-like class. After that, we created an object for student class ‘s1’ using which we can access the data member of the student class and anonymous union members. So, using object ‘s1’ we assign values to class data members and union data members and then print their values.
Similar Reads
C++ Unions
In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory sepa
5 min read
C++ Map of Functions
Prerequisites: Functions in C++Map in C++ Maps in C++ are a very useful data structure for storing key-value pairs. A map is the best way to store where we can directly find and access the value using a key with the best time complexity. However, did you know that you can also store functions as val
5 min read
SQL UNION ALL
UNION ALL Operator is used to combine the results of two or more SELECT statements into a single result set. Unlike the UNION operator, which eliminates duplicate records and UNION ALL includes all duplicates. This makes UNION ALL it faster and more efficient when we don't need to remove duplicates.
4 min read
std::set_union in C++
Union of two sorted ranges The union of two sets is formed by the elements that are present in either one of the sets, or in both. Elements from the second range that have an equivalent element in the first range are not copied to the resulting range.The elements are compared using operator< for
5 min read
std::plus in c++
It is a Function object for performing addition. The object class whose call returns the result of adding its two arguments (as returned by operator + ). Syntax : template struct plus : binary_function { T operator() (const T& x, const T& y) const { return x + y; } }; Template parameters : T
2 min read
C++ Identifiers
In C++ programming language, identifiers are the unique names assigned to variables, functions, classes, structs, or other entities within the program. Let's take a look at an example: [GFGTABS] C++ // Creating a variable int val = 10; // Creating a function void func() {} [/GFGTABS]In this above co
3 min read
Literals in C++
In C++ programming language, literals are fundamental elements used to represent fixed values. These values can include numbers, characters, strings, and more. They are generally present as the right operand in the assignment operation. Let's take a look at an example: [GFGTABS] C++ #include <ios
6 min read
Operators in C++
In C++, an operator is a symbol that operates on a value to perform specific mathematical or logical computations on given values. They are the foundation of any programming language. Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a;
9 min read
merge() in C++ STL
C++ offers in its STL library a merge() which is quite useful to merge sort two containers into a single container. It is defined in header "algorithm". It is implemented in two ways. Syntax 1 : Using operator "<" Template : template outiter merge (initer1 beg1, initer1 end1, initer2 beg2, initer
5 min read
set::insert() function in C++ STL
The std::set::insert() is a built-in function of C++ STL set container which is used to insert new elements in it. In this article, we will learn how to use set::insert() function in our C++ programs. SyntaxThe string::replace() function provides 6 different overloads for different purposes: st.inse
4 min read