next up previous
Next: Classes Up: Overview of C++ Previous: Accessing Structure Members

Unions

In C++ a union is a memory location that is shared by two or more different variables. The union definition is similar to that of structures as shown in this example:

union utype{
int i;
char ch; };

As with structures, a union declaration doesn't define any variables. You may declare a variable either by placing its name at the end of the definition or by using a separate declaration statement. To declare a union variable called u_var of type utype using the definition just given, you would write

utype u_var;

In u_var, both integer i and character ch share the same memory location. When a union is declared, the compiler will automatically allocate enough storage to hold the largest variable type in the union.

To access a union element, use same syntax as that you would use for structures. For example to assign the letter A to element ch of u_var you would write the following:

u_var.ch='A';

This is the last section that describes those attributes of C++ that are not explicitly object-oriented. Beginning with the next section, features that supports object oriented programming (OOP) will be examined.



Yousef Haik
2/23/1998