Skip to Main Content
C++ In a Nutshell
book

C++ In a Nutshell

by Ray Lischner
May 2003
Intermediate to advanced content levelIntermediate to advanced
808 pages
32h 24m
English
O'Reilly Media, Inc.
Content preview from C++ In a Nutshell

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

See Also

class, struct, Chapter 2, Chapter 6

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ High Performance

C++ High Performance

Viktor Sehr, Björn Andrist
Optimized C++

Optimized C++

Kurt Guntheroth
Mastering C++ Programming

Mastering C++ Programming

Jeganathan Swaminathan

Publisher Resources

ISBN: 059600298XSupplemental ContentErrata Page