C++ Structures and Unions - What's the Difference


In C++, structures and unions are user-defined data types that allow you to group multiple variables of different data types under a single name. While they serve a similar purpose, they have significant differences in how they store and manage data. In this guide, we'll explore the distinctions between structures and unions and provide sample code to illustrate their usage.


C++ Structures

Structures in C++ are used to group variables of different data types under a single name. Each variable within a structure occupies its own memory location. Here's how to define and use a structure:


#include <iostream>
using namespace std;
// Define a structure
struct Person {
string name;
int age;
};
int main() {
// Create an instance of the structure
Person person1;
person1.name = "Alice";
person1.age = 30;
cout << "Name: " << person1.name << endl;
cout << "Age: " << person1.age << endl;
return 0;
}

C++ Unions

Unions are similar to structures but with a key difference: all variables within a union share the same memory location. This means only one variable can be stored and accessed at a time. Here's how to define and use a union:


#include <iostream>
using namespace std;
// Define a union
union Value {
int intValue;
double doubleValue;
};
int main() {
// Create an instance of the union
Value value;
value.intValue = 42;
// Access the integer value
cout << "Integer Value: " << value.intValue << endl;
value.doubleValue = 3.14;
// Access the double value (value.intValue is now overwritten)
cout << "Double Value: " << value.doubleValue << endl;
return 0;
}

Differences Between Structures and Unions

The main differences between structures and unions are:

  • In structures, each member has its own memory location, allowing simultaneous access to all members. In unions, members share the same memory location, and only one member is accessible at a time.
  • Structures are used when you need to store multiple data items together. Unions are used when you want to save memory by storing only one data item at a time.

Conclusion

Structures and unions are valuable tools in C++ for grouping variables of different data types. Understanding their differences is essential to choose the right one for your specific programming needs. As you continue your C++ journey, you'll find structures and unions useful for organizing and managing data.