Union-like Classes in C++
A union-like class is just a class with at least one anonymous union defined inside it and the data members defined in an anonymous union are known as variant members.
Example: C++ program to illustrate Union-like classes
C++
#include <iostream> #include <string> using namespace std; // Creating a union-like class class student { public : // Declaring class data members. string name; // Creating a anonymous union without a name. union { // Defining data members int standard; char section; }; }; int main() { // Creating an object of myClass. student s1; // Assigning values to class members and printing them. s1.name = "geek" ; cout << "Name : " << s1.name << endl; // Assigning value to anonymous class member standard s1.standard = 9; cout << "Standard : " << s1.standard << endl; // Assigning value to anonymous class union member // section s1.section = 'D' ; cout << "Section : " << s1.section << endl; return 0; } |
Name : geek Standard : 9 Section : D
Explanation
In the above example, we have created a class ‘student’ a data member, and an anonymous union inside it which is called a union-like class. After that, we created an object for student class ‘s1’ using which we can access the data member of the student class and anonymous union members. So, using object ‘s1’ we assign values to class data members and union data members and then print their values.
C++ Unions
In C++, a union is a user-defined datatype in which we can define members of different types of data types just like structures. But one thing that makes it different from structures is that the member variables in a union share the same memory location, unlike a structure that allocates memory separately for each member variable. The size of the union is equal to the size of the largest data type.
Memory space can be used by one member variable at one point in time, which means if we assign value to one member variable, it will automatically deallocate the other member variable stored in the memory which will lead to loss of data.
Contact Us