The purpose of a C++ union 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 c++ union is only as big as necessary to hold its largest data members. The other members of the union, 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 C++ union

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

When you are using visual studio, if you declare a union globally, the union you declared must be with the static keyword. This just means it will reside in the memory till the 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
#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