Namespaces
Variants
Views
Actions

Union declaration

From cppreference.com
< cpp‎ | language
Revision as of 14:11, 14 March 2013 by Bazzy (Talk | contribs)

 
 
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

Syntax

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

Explanation

  1. Named union
  2. Anonymous union

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.

Example

#include <iostream>
 
union {
    int x;
    signed char y;
} foo;
 
int main()
{
    foo.x = 1023;
    std::cout << "as int: "  << (int)foo.x << '\n';
    std::cout << "as char: " << (int)foo.y << '\n';
}

Possible output:

as int: 1023
as char: -1