Name
union keyword — Declares a union
Synopsis
class-key := union
The union
keyword declares an
aggregate type, similar to a struct
, but the union object can store only
one member at a time. The storage for all members overlaps. A union
can have member functions (including constructors and destructors) but
not virtual member functions. A union cannot be or have a base class.
Union members cannot be static or references. Data members cannot have
constructors, a destructor, copy-assignment operators, virtual
functions, or virtual base classes. An initializer for a union can
initialize only its first member.
See class
for the syntax
rules.
Example
enum kind { integer, real, text };
struct data {
kind data_kind;
data(int i) : data_kind(integer), integerval(i) {}
data(double d) : data_kind(real), realval(d) {}union
{
int integerval;
double realval;
};
};
Get C++ In a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.