Union, Part 2
Now, we lets move to a little complicated example with struct inside union with multiple size:
Here is a example:
#include <iostream>
struct Vector1
{
int a, b;
};
struct Vector2
{
union
{
struct
{
int a,b,c,d;
};
struct
{
Vector1 x,y;
};
};
};
void printVector1(Vector1& v1) {
std::cout << v1.a << ", " << v1.b << std::endl;
}
int main(int argc, char const *argv[])
{
Vector2 v = {1,2,3,4};
printVector1(v.x);
printVector1(v.y);
v.d = 500;
printVector1(v.x);
printVector1(v.y);
return 0;
}Try it here:
Output:
1, 2
3, 4
1, 2
3, 500Lets explore this example:
Here, we created 2 structs,
Vector1andVector2.Vector1contains two integers:a,b.Vector2contains two possible values based on union, either it will have four integersa,b,c,dor it will contain 2Vector1.Now, if we create an object of
Vector2with values{1, 2, 3, 4}.This
Vector2instance can be converted into two instances ofVector1as it was part of the vector.And, if we update a value of
Vector2insrance and read it asVector1Instance, you will see thatVector1data has been changes as they are referring to same memory location.
Last updated