I know that we can access anonymous unions without creating it's object(without dot), but could anybody please explain,what is the use of anonymous unions in real world c++ programing?
I have mostly used unions to store multiple different types of elements in the same contiguous storage without resorting to dynamic polymorphism. Thus, every element of my union is a struct describing the data for the corresponding node type. Using an anonymous union mostly gives a more convenient notation, i.e. instead of object.union_member.struct_member
, I can just write object.struct_member
, since there is no other member of that name anyways.
A recent example where I used them would be a rooted (mostly binary) tree which has different kinds of nodes:
struct multitree_node {
multitree_node_type type;
...
union {
node_type_1 n1;
node_type_2 n2;
...
};
};
Using this type tag type
I am able to determine which element of the union to use. All of the structs node_type_x
have roughly the same size, which is why I used the union in the first place (no unused storage).
With C++17, you would be able to do this using std::variant
, but for now, using anonymous unions are a convenient way of implementing such 'polymorphic' types without virtual
functions.
Here's a real-world example:
struct Point3D {
union {
struct {
float x, y, z;
};
struct {
float c[3];
};
};
};
Point3D p;
You can access p
's x/y/z coordinates with p.x
, p.y
, p.z
. This is convenient.
But sometimes you want to access point as a float[3]
array. You can use p.c
for that.
Note: Using this construct is Undefined Behavior by the standard. But, it works on all compilers I've met so far. So, if you want to use such a construct, be aware, that this may broke some day.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With