Union Declarations

From RAD Studio
Jump to: navigation, search

Go Up to Unions Index

The general declaration syntax for unions is similar to that for structures. The differences are:

  • Unions can contain bit fields, but only one can be active. They all start at the beginning of the union. (Note that, because bit fields are machine dependent, they can pose problems when writing portable code.)
  • Unlike C++ structures, C++ union types cannot use the class access specifiers: public, private, and protected. All fields of a union are public.
  • Unions can be initialized only through their first declared member:
union local87 {
   int i;
   double d;
   } a = { 20 };

A union can't participate in a class hierarchy. It can't be derived from any class, nor can it be a base class. A union can have a constructor.

Unrestricted unions

Starting with C++11, some of the restrictions mentioned above have been disabled.

Unions can now contain objects that have a non-trivial constructor. If a union contains such an object, the implicit default constructor of the union is deleted, forcing the user to manually define a constructor. For example:

#include <new> // Required for placement 'new'.
 
struct 3DPoint {
    3DPoint() {}
    3DPoint(int x, int y, int z): x_(x), y_(y), z_(z) {}
    int x_, y_, z_;
};
 
union U {
    double w;
    3DPoint p; // Allowed in C++11.
    U() {new(&p) 3DPoint();} // Due to the 3DPoint member, a user-defined constructor is now required.
};

See Also