The purpose of unions in C++

The purpose of unions in C++ is simply a user defined type that is similar to the struct keyword but instead all members share the same memory location. The memory location is shared by two or more variables as the union is only as big as necessary to hold its largest data members. With the other members of the union, they are allocated in the same bytes as part of that largest member.

union diagram

Unions can be useful for conserving memory when you have lots of objects or limited memory (think embedded applications).

Anonymous unions

The key thing to remember with an anonymous union is that it does not include a type name. It tell’s the compiler that its members share the same location and can be directly referred without the dot operator, like when using classes and structures.

When you are using visual studio, if you declare an union globally, the union you declared must be with the static keyword. This just means it will reside in the memory till end of the program.

The restrictions with Anonymous unions include

  • Unions can’t be declared with reference variables
  • Unions can’t be declared with virtual functions
  • It’s not possible to inherit from a union or derive a union from another class
<pre>#include <iostream>
using namespace std;

static union
long l;
double d;
char s[4];

int main()
l = 10000;
cout << l << "\t";

d = 123.2342;
cout << d << "\t";

strcpy_s(s, "hello");
cout << s << "\n";
Share this post