
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Hello World
- C++ Omitting Namespace
- C++ Tokens
- C++ Constants/Literals
- C++ Keywords
- C++ Identifiers
- C++ Data Types
- C++ Numeric Data Types
- C++ Character Data Type
- C++ Boolean Data Type
- C++ Variable Types
- C++ Variable Scope
- C++ Multiple Variables
- C++ Basic Input/Output
- C++ Modifier Types
- C++ Storage Classes
- C++ Numbers
- C++ Enumeration
- C++ Enum Class
- C++ References
- C++ Date & Time
- C++ Operators
- C++ Arithmetic Operators
- C++ Relational Operators
- C++ Logical Operators
- C++ Bitwise Operators
- C++ Assignment Operators
- C++ sizeof Operator
- C++ Conditional Operator
- C++ Comma Operator
- C++ Member Operators
- C++ Casting Operators
- C++ Pointer Operators
- C++ Operators Precedence
- C++ Unary Operators
- C++ Control Statements
- C++ Decision Making
- C++ if Statement
- C++ if else Statement
- C++ Nested if Statements
- C++ switch Statement
- C++ Nested switch Statements
- C++ Loop Types
- C++ while Loop
- C++ for Loop
- C++ do while Loop
- C++ Foreach Loop
- C++ Nested Loops
- C++ break Statement
- C++ continue Statement
- C++ goto Statement
- C++ Strings
- C++ Strings
- C++ Loop Through a String
- C++ String Length
- C++ String Concatenation
- C++ String Comparison
- C++ Functions
- C++ Functions
- C++ Multiple Function Parameters
- C++ Recursive Function
- C++ Return Values
- C++ Function Overloading
- C++ Function Overriding
- C++ Default Arguments
- C++ Arrays
- C++ Arrays
- C++ Multidimensional Arrays
- C++ Pointer to an Array
- C++ Passing Arrays to Functions
- C++ Return Array from Functions
- C++ Structure & Union
- C++ Structures
- C++ Unions
- C++ Pointers
- C++ Pointers
- C++ Dereferencing
- C++ Modify Pointers
- C++ Class and Objects
- C++ Object Oriented
- C++ Classes & Objects
- C++ Class Member Functions
- C++ Class Access Modifiers
- C++ Static Class Members
- C++ Static Data Members
- C++ Static Member Function
- C++ Inline Functions
- C++ this Pointer
- C++ Friend Functions
- C++ Pointer to Classes
- C++ Constructors
- C++ Constructor & Destructor
- C++ Default Constructors
- C++ Parameterized Constructors
- C++ Copy Constructor
- C++ Constructor Overloading
- C++ Constructor with Default Arguments
- C++ Delegating Constructors
- C++ Constructor Initialization List
- C++ Dynamic Initialization Using Constructors
- C++ Inheritance
- C++ Inheritance
- C++ Multiple Inheritance
- C++ Multilevel Inheritance
- C++ Object-oriented
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
- C++ Virtual Function
- C++ Pure Virtual Functions & Abstract Classes
- C++ File Handling
- C++ Files and Streams
- C++ Reading From File
- C++ Advanced
- C++ Exception Handling
- C++ Dynamic Memory
- C++ Namespaces
- C++ Templates
- C++ Preprocessor
- C++ Signal Handling
- C++ Multithreading
- C++ Web Programming
- C++ Socket Programming
- C++ Concurrency
- C++ Advanced Concepts
- C++ Lambda Expression
- C++ unordered_multiset
Unions in C++
In C++, a union is a user-defined data type that allows you to store different data types in the same memory location. However, the union can store only one of its member variables at a time, which means that if you assign a value to one member, the previous value stored in another member is overwritten. Where the size of a union is determined by the size of its largest member.
Union Declaration
To declare a union, use the union keyword followed by the tag_name (union name) and then declare the union members with their data types inside the curly brackets. Close the declaration with a semicolon.
Below is the syntax to declare a union −
union UnionName { dataType1 member1; dataType2 member2; // more members };
Example
Here's a short example based on the above syntax to declare a union −
union UnionName { int intValue; // Member for integer value float floatValue; // Member for float value char charValue; // Member for character value };
Declaring Union Variable
After declaring a union, you need to declare its variable to access and manipulate its members.
Below is the syntax to declare a union variable −
union_name variable;
Accessing Union Members
You can access union members using the dot operator (.) after declaring a union variable.
Below is the syntax to access union members -
union_variable.member
Example of C++ Union
Here's a full example of a union demonstrating it's working −
#include <iostream> #include <cstring> using namespace std; union Data { int intValue; // Member for integer value float floatValue; // Member for float value char strValue[50]; // Member for string value }; int main() { // Defining a union variable Data data; data.intValue = 2006; cout << "TutorialsPoint: Founded in " << data.intValue << endl; // overwrites the previous integer value data.floatValue = 5.75f; cout << "My Float value is: " << data.floatValue << endl; // overwrites the previous float value strcpy(data.strValue, "Hello TutorialsPoint Learner"); cout << data.strValue << endl; // Accessing the integer after assigning a string cout << "Integer after string assignment: " << data.intValue << endl; // Undefined behavior return 0; }
When the above code is compiled and executed, it produces the following result −
TutorialsPoint: Founded in 2006 My Float value is: 5.75 Hello TutorialsPoint Learner Integer after string assignment: 1819043144
Explanation
The above-given example demonstrates the use of a union, how it is created and accessed,
- Firstly, a union named Data is defined with three members: int intValue, float floatValue, char strValue[50], where only one of these members can hold a value at any given time.
- As the size of the union is determined by the largest member so in this case (the char array).
- A union variable data is declared in the int main() body.
- To assign and access members, all the members are assigned their values by using "." as data.intValue respectively.
- For float value, the float member floatValue is assigned the value 5.75.
- However, since a union can only hold one value at a time the previous value of intValue is overwritten, though it will still occupy the same memory space.
- Now at last finally when the code attempts to print intValue after it has been overwritten by the string assignment. This leads to undefined behavior, the integer value is no longer valid, and accessing it may give unexpected results as given in the output.
Anonymous Unions
Anonymous unions are a special type of union which don't have a name. This helps in simplifying code by allowing you to direct access to union members without specifying the union variable name.
Syntax
Here's a simple syntax for Anonymous Union, which is declared without any name, allowing direct access to its members −
union { dataType1 member1; dataType2 member2; // additional members... };
Example
Here's an example of the above-based syntax for the anonymous union −
#include <iostream> #include <cstring> using namespace std; // Use the standard namespace int main() { // Anonymous union declaration union { int intValue; float floatValue; char strValue[50]; }; // Assigning an integer value intValue = 2006; cout << "Integer Value: " << intValue << endl; // Assigning a float value (overwrites the previous integer value) floatValue = 3.14 f; cout << "Float Value: " << floatValue << endl; // Assigning a string value (overwrites the previous float value) strcpy(strValue, "Hello, TutorialsPoint Learner!"); cout << "String Value: " << strValue << endl; // Accessing the integer after string assignment (undefined behavior) cout << "Integer after string assignment: " << intValue << endl; return 0; }
When the above code is compiled and executed, it produces the following result −
Integer Value: 2006 Float Value: 3.14 String Value: Hello, TutorialsPoint Learner! Integer after string assignment: 1819043144
Union-like Classes
In C++ a union-like class is defined as a class that includes at least one anonymous union as a member. The data members defined within these anonymous unions are known as variant members. It is the data structures that encapsulate the concept of a union but provide additional features for type safety and usability.
These typically use a combination of member variables and a mechanism (like an enumerator) to track which type is currently active.
Syntax
Here's a basic syntax for Union-like classes where the class keyword is used to define the class, followed by the class name class name (here, UnionLikeClass)
class UnionLikeClass { public: union { dataType1 member1; // Member of type dataType1 dataType2 member2; // Member of type dataType2 // additional members... }; };
Example
Here's an example of Union-like classes based on the above syntax:
#include <iostream> #include <cstring> using namespace std; class UnionLikeClass { public: // Anonymous union declaration union { int intValue; // Member for integer value float floatValue; // Member for float value char strValue[50]; // Member for string value }; // Method to display the current value void display() { cout << "Integer Value: " << intValue << endl; cout << "Float Value: " << floatValue << endl; cout << "String Value: " << strValue << endl; } }; int main() { // Creating an instance of UnionLikeClass UnionLikeClass data; data.intValue = 2006; cout << "TutorialsPoint: Founded in " << data.intValue << endl; data.floatValue = 3.14f; cout << "Assigned Float Value: " << data.floatValue << endl; // Assigning a string value (overwrites the previous float value) strcpy(data.strValue, "Hello, Union Like Class!"); cout << "Assigned String Value: " << data.strValue << endl; // Accessing the integer after string assignment (undefined behavior) cout << "Integer after string assignment: " << data.intValue << endl; // Undefined behavior return 0; }
TutorialsPoint: Founded in 2006 Assigned Float Value: 3.14 Assigned String Value: Hello, Union Like Class! Integer after string assignment: 1819043144