Website For Developers

Unions in C++


  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


Example of Unions in C++

using namespace std;

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

  cout<<endl<<endl<<"Enter Name: ";
  cin>>; //access structure member name
  cout<<"Name is: "<<;
  return 0;


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.