Union declaration
This section is incomplete Reason: Expand description and example |
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
- Named union
- 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
Output:
as int: 1024 as char: 128
(for little-endian processors)