Union
(C++)
A union in C++ is a user-defined type that can hold different types of data, but only one type at a time.
It’s like a struct, but all members share the same memory location.
union Number {
int intVal;
float floatVal;
};
Number num;
num.intVal = 5; // num holds an integer
num.floatVal = 7.5; // now num holds a float, and the integer value is overwritten
Resources
Can different member fields are different sizes?
Yes, different members of a union can have different sizes in bits. The size of the union is determined by the size of its largest member.
An example for exception handling
optional<int*> Malloc(size_t size) {
if (random() % 2) return (int*)malloc(sizeof(int));
return nullopt; // no storage
}
optional<int> rtn() {
optional<int*> p = Malloc(sizeof(int));
if (!p) return nullopt; // malloc successful (true/false) ?
**p = 7; // compute
if (random() % 2) return **p;
return nullopt; // bad computation
}
int main() {
srandom(getpid());
optional<int> ret = rtn();
if (ret) cout << *ret << endl; // rtn successful?
}