Union declaration

From cppreference.com
 
 
C++ language
General topics
Preprocessor
Comments
Keywords
ASCII chart
Escape sequences
History of C++
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
union types
function types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

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)