DekGenius.com
Team LiB   Previous Section   Next Section
union keyword Declares a union

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;
  };
};

See Also

class, struct, Chapter 2, Chapter 6

    Team LiB   Previous Section   Next Section