I have a question about something I still don't understand about unions. I've read about a lot of their uses and for the most part can see how they can be useful and understand them. I've seen that they can provide a primitive "C style" polymorphism. The example of this that I have seen on a couple websites is SDL's event union:
typedef union {
Uint8 type;
SDL_ActiveEvent active;
SDL_KeyboardEvent key;
SDL_MouseMotionEvent motion;
SDL_MouseButtonEvent button;
SDL_JoyAxisEvent jaxis;
SDL_JoyBallEvent jball;
SDL_JoyHatEvent jhat;
SDL_JoyButtonEvent jbutton;
SDL_ResizeEvent resize;
SDL_ExposeEvent expose;
SDL_QuitEvent quit;
SDL_UserEvent user;
SDL_SysWMEvent syswm;
} SDL_Event;
What I cannot understand is how there can be a "type" member up there coexisting with the event types? Aren't these each only allowed to exist one at a time since they occupy the same area of memory? Wouldn't the union exist at any time as EITHER a type or one of the events?
I understand that each event is actually a struct with a type member, for example:
// SDL_MouseButtonEvent
typedef struct{
Uint8 type;
Uint8 button;
Uint8 state;
Uint16 x, y;
} SDL_MouseButtonEvent;
How does this somehow make sense? Does this somehow allow the type member of the union represent the type of whatever struct the union is currently? Is this some sort of bizarre effect that happens when every member of the union except one is a struct and each struct contains that one member?
Can you access struct members without knowing which struct the object is?
Thanks!