Union declaration

From cppreference.com
 
 
C++ language
General topics
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)
Initialization
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, be inherited or inherit other classes.

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

(since C++11) If a union contains a non-POD member, which has a user-defined special function (constructor, destructor, copy constructor or copy assignment) that function is deleted by default in the union and needs to be defined explicitly by the user.

Contents

[edit] Syntax

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

[edit] Explanation

  1. Named union
  2. Anonymous union

[edit] Anonymous unions

Members of an anonymous union are accessible from the enclosing scope as single variables.

Anonymous unions have further restrictions: they must have only public members and cannot have member functions.

Namespace-scope anonymous unions must be static.

[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)