Relationship between Unions and Classes
unions and classes are related concepts that share many similarities. Like structures, unions can be used to define a class that can contain both member functions and variables, including constructors and destructors. A union in C++ retains all of its C-like features, with the most important one being that all data elements share the same location in memory. This means that changing the value of one member will affect the value of all the other members.
In the following example, a union is used to swap the bytes that make up an unsigned short integer
copy
#include <iostream>
using namespace std;
union swap_byte {
void swap();
void set_byte(unsigned short i);
void show_word();
unsigned short u;
unsigned char c[2];
};
void swap_byte::swap()
{
unsigned char t;
t = c[0];
c[0] = c[1];
c[1] = t;
}
void swap_byte::show_word()
{
cout << u;
}
void swap_byte::set_byte(unsigned short i)
{
u = i;
}
int main()
{
swap_byte b;
b.set_byte(49034);
b.swap();
b.show_word();
return 0;
}
Like a structure, a union declaration in C++ defines a special type of class. This means that the principle of encapsulation is preserved. However, there are several restrictions that must be observed when using C++ unions. For example, a union cannot inherit any other classes of any type, cannot be a base class, and cannot have virtual member functions.
Anonymous Union
Another type of union in C++ is the anonymous union, which does not include a type name and no objects of the union can be declared. Instead, an anonymous union tells the compiler that its member variables are to share the same location. However, the variables themselves are referred to directly, without the normal dot operator syntax.
Here's an example of how an anonymous union can be used
copy
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
// define anonymous union
union {
long l;
double d;
char s[4];
};
// now, reference union elements directly
l = 100000;
cout << l << " ";
d = 123.2342;
cout << d << " ";
strcpy(s, "hi");
cout << s;
return 0;
}
As you can see, the elements of the union are referenced as if they had been declared as normal local variables. However, it's worth noting that the names of the members of an anonymous union must not conflict with other identifiers known within the same scope.
Summary
unions and classes in C++ are closely related, and understanding how they work can help you write more efficient and effective code. By knowing the restrictions that apply when using C++ unions, you can ensure that your programs run smoothly and efficiently.