3.12 UNION

When we define a record using construct “struct”, memory is reserved for all of its members. In data processing applications, sometimes a situation occurs where only one of the members is relevant. In Pascal such records were called variant records. In C++, they are called as unions. Here memory is allocated to accommodate only the largest member. Considering the fact that in typical programs, we handle large number of records using union results in saving a lot of memory.

Let us study how to define a union.

3.12.1 Defining an union

A typical union declaration is shown below:

union T1{ int    x ;

          float y ;

        };

Notice the following:

  1. Declaration starts with keyword “union”.
  2. This union is named (type name) as T1. (Like ...

Get Object Oriented Programming with C++, Second Edition 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.