C++ has a structure that allows us to have different types of data within the same variable. A union
is particularly memory efficient as it calculates the minimum amount of memory to store the largest element in the structure.
Therefore, contained data overlaps in memory.
#include <iostream>
using namespace std;
union StudentID {
char* byName; // memory for a pointer OR
int byNumber; // memory for an int
};
int main()
{
StudentID s;
s.byNumber = 12345;
cout << s.byNumber << endl; //outputs 12345
s.byName = "Hello";
cout << s.byName << endl; //outputs Hello
cout << s.byNumber << endl; //outputs 4198928
}
© 2006
Dr. Derek Molloy
(DCU).