Namespaces
Variants
Views
Actions

Union declaration

From cppreference.com
< cpp | language
Revision as of 17:40, 19 April 2012 by P12bot (Talk | contribs)

Template:cpp/language/sidebar

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.

Syntax

union Template:sparam { Template:sparam } Template:sparam ; (1)
union { Template:sparam } Template:sparam ; (2)

Explanation

  1. Named union
  2. Unnamed union

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)