The Wayback Machine - https://web.archive.org/web/20120425192318/http://en.cppreference.com:80/w/cpp/language/union

Union declaration

From cppreference.com
Jump to: navigation, search

A union is a special class type that stores all of its data members in the same memory location.

Unions cannot have virtual functions and cannot be inherited.

(until C++11) Unions can only contain POD (plain old data) types.

(since C++11) Unions can contains non-trivial types provided that eventual non-trivial constructors are defined by the user.

[edit] Syntax

union name { member_declarations } object_list (optional) ; (1)
union { member_declarations } object_list ; (2)

[edit] Explanation

  1. Named union
  2. Unnamed union

[edit] Example

union foo
{
  int x;
  signed char y;
};
 
int main()
{
  foo.x = 128 + 896;
  std::cout << "as int: "  << (int)foo.x << '\n';
  std::cout << "as char: " << (int)foo.y << '\n';
  return 0;
}

Output:

as int: 1024
as char: 128

(for little-endian processors)

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages