Jump to content

C++ Programming

From Wikibooks, open books for an open world

The union keyword is used to define a union type.

Syntax
    union union-name 
    {
        public-members-list;
    private:
        private-members-list;
    } object-list;

Union is similar to struct (more than class), unions differ in the aspect that the fields of a union share the same position in memory and are by default public rather than private. The size of the union is the size of its largest field (or larger if alignment so requires, for example on a SPARC machine a union contains a double and a char [17] so its size is likely to be 24 because it needs 64-bit alignment). Unions cannot have a destructor.

What is the point of this? Unions provide multiple ways of viewing the same memory location, allowing for more efficient use of memory. Most of the uses of unions are covered by object-oriented features of C++, so it is more common in C. However, sometimes it is convenient to avoid the formalities of object-oriented programming when performance is important or when one knows that the item in question will not be extended.

     union Data {
       int i;
       char c;
     };

The use of union is covered in greater detain in the Unions Section.