Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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
Advertisements