C++ Language
Union Declaration
A union is a user-defined data type that allows you to define a structure where all members share the same memory space. Unlike structures, where each member has its own separate memory space, members of a union occupy the same memory location. The size of a union is determined by the size of its largest member.
Here's the basic syntax for declaring a union in C++:
union MyUnion { // Members share the same memory space int member1; double member2; char member3; // ... more members if needed };
• Let's break down the components:
⤏ 'union': This keyword is used to define a union in C++.
⤏ 'MyUnion': This is the name of the union. You can choose any valid identifier as the union name..
⤏ '{ /* Members */ }': This block contains the members of the union. Each member is declared with its data type and a name. In the example above, 'member1' is an integer, 'member2' is a double, and 'member3' is a character. You can add more members as needed.
Here's an example of how to use a union in C++:
#include<iostream> union MyUnion { int member1; double member2; char member3; }; int main() { MyUnion myObject; myObject.member1 = 42; myObject.member2 = 3.14; myObject.member3 = 'A'; // Display the values std::cout << "Member 1: " << myObject.member1 << std::endl; std::cout << "Member 2: " << myObject.member2 << std::endl; std::cout << "Member 3: " << myObject.member3 << std::endl; // Display the size of the union std::cout << "Union Size: " << sizeof(MyUnion) << " bytes" << std::endl; return 0; }
In this example, the members of the union ('member1', 'member2', and 'member3') share the same memory space. Modifying one member may affect the values of the other members.
Member 1: 1374389569 Member 2: 3.14 Member 3: A Union Size: 8 bytes
Note: That the size of the union is determined by the size of its largest member ('double' in this case).
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.