Home

Unions

 

Introduction

A union is another type of class of the C++ language. Like the other two, it is created from combining other identified variables. To create a union, use the union keyword following the same syntax applied for a structure, like this:

union UnionName {};

Like another class, the members of a union are listed in its body. For example, to create an object that represents a student, using a union, you could define it as follows:

union CHouseAge
{
    int YearBuilt;
    int Age;
};

Once the union is defined, you can declare it and use its members:

using namespace System;

union CHouseAge
{
    int YearBuilt;
    double Age;
};

int main()
{	
    CHouseAge home;

    home.YearBuilt = 1972;
	
    Console::Write("The house was built in = ");
    Console::WriteLine(home.YearBuilt);

    return 0;
}

This would produce:

The house was built in = 1972
Press any key to continue . . .

Using a Union

When creating a class of struct or class type, each variable, treated as its own entity, occupies its assigned amount of space in memory. This is different with unions. All of the members of a union share the same memory space. After declaring a union object, instead of allocating memory for each member variable, the compiler assigns an amount of memory equal to the largest variable. If you define a union that would represent a CHouseAge object as the above, the compiler would assign the same memory space to all members; and the compiler would find out which member needs the largest space. In our example, the Age member variable uses more memory than the YearBuilt. Therefore, the compiler will allocated the amount of memory required by a double, then all member variables would share that memory. Consequently, a union can store the value of only one of its members at a time: you cannot simultaneously access the values of all members, at the same time. If you initialize all of the members of a union at the same time, the result is unreliable; since all members are using the same memory space, that space cannot accommodate all member values at the same time.

Because only one member of a union can be considered for an instance of the object, use a union you are in an "either of one" scenario. For example, when processing our CHouseAge object, we want Either the year the house was built OR its age. We don't need both values. In fact this would create redundancy in the program. Notice that, if we know the year the house was built, we can deduct its age. On the other hand, if we know the age of the house, we can calculate the year it was built.


Previous Copyright © 2006-2007 FunctionX, Inc. Next