Union, Part 2
Now, we lets move to a little complicated example with struct inside union with multiple size:
Here is a example:
Try it here:
Output:
Lets explore this example:
Here, we created 2 structs,
Vector1
andVector2
.Vector1
contains two integers:a
,b
.Vector2
contains two possible values based on union, either it will have four integersa
,b
,c
,d
or it will contain 2Vector1
.Now, if we create an object of
Vector2
with values{1, 2, 3, 4}
.This
Vector2
instance can be converted into two instances ofVector1
as it was part of the vector.And, if we update a value of
Vector2
insrance and read it asVector1
Instance, you will see thatVector1
data has been changes as they are referring to same memory location.
Last updated