Search code examples
c++unions

Assignment to unions of members


Let's say I have a class with union members in it:

class ClassX {
public:
  union {
    StructA * A;
    StructB * B;
    };
  }

If I have pointers x1 and x2 to different ClassX objects, does this:

x1->A = x2->A;

Have the same effect as this:

x1->B = x2->B;

? Thanks.


Solution

  • For most practical purposes, on most implementations, those two statements would have the same effect, however it's not guaranteed. If the member that you read from a union isn't the last member that was writted to the union the behaviour of the program is undefined.

    Because both members of the union are pointers to structs it is very likely that they occupy the same size and have analogous representations so assigning either union member is likely to correctly assign the other union member if that's what was actually stored in the source union.