Website For Developers

Unions in C++




Syntax

  union example {
   //union members
   int number;
   string name;
};

Syntax of defining union variable

  example obj;
  //example is the union name and obj is the union variable name.

Syntax to access union members

  obj.number;
  obj.name;


Example of Unions in C++

#include<iostream>
#include<conio.h>
using namespace std;

//union declaration
union demo {
  int id;
  char name[20];
};
int main() {
  //defining structure variable
  demo obj;
  cout<<"Enter ID: ";
  cin>>obj.id; //access structure member id
  cout<<"ID is: "<<obj.id;

  cout<<endl<<endl<<"Enter Name: ";
  cin>>obj.name; //access structure member name
  cout<<"Name is: "<<obj.name;
  getch();
  return 0;
}

Output

Enter ID: 808
ID is: 808

Enter Name: Braca
Name is: Braca


Difference between Union and Structure

Structure Unions
Structure starts with struct keyword. Union starts with union keyword
Structure allocates/assign different memory locations for its members. Union in C++ allocates/assign common memory location for its members.
All structure members can initialize at a time. Only one union member can initialize at a time.
Structures in c++ are used when all members are to be used independently. Unions in c++ are used when all members are not to be access at the same time.