Hey
I was wondering what is the difference between classes unions and structs?
They all seem to be the same
Hey
I was wondering what is the difference between classes unions and structs?
They all seem to be the same
And a union is different from both struct and class in that ALL of the data members in a union are placed at the same postion [so they are overlaying each other in the same place in memory].
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
wonder who named it union then. A preacher perhaps, surely not a mathematician.
touche.
I don't know, "rug" perhaps?
If you draw a Venn diagram of the variables in your memory, it is a union.
Ahhh...so of all the data types in the union, the union can only be one of these?
A union such as:
simply causes i, c & f to begin at the same memory address.Code:union abc { int i; char c; float f; };
If you set i to 0x01020304, then read c, you should see 0x01 or 0x04 (depending on whether you're on a Big Endian or Little Endian system).
Just think of it as having a block of memory and just casting it to int, char, or float...
Yes.
For example,
The union allows you to store an integer OR a double (but not both at the same time). The size of the union should be 8 bytes, the first 4 are shared. That means writing to one variable will 'overwrite' the other variable.Code:union MyUnion { int n; double d; }; struct MyStruct { int n; double d; };
The struct allows you to store an integer AND a double at the same time, because it makes enough room for both variables, which should be 12 bytes.
Ahh I understand now...
I don't see them much, what are they used for generally?
What are they useful for?
I've seen them used in Windows API. For example the INPUT_RECORD struct looks like this:
This single struct can store data about various events, each requiring different fields. Which event record contains valid data is determined by EventType, other records are just garbage.Code:typedef struct _INPUT_RECORD { // ir WORD EventType; union { KEY_EVENT_RECORD KeyEvent; MOUSE_EVENT_RECORD MouseEvent; WINDOW_BUFFER_SIZE_RECORD WindowBufferSizeEvent; MENU_EVENT_RECORD MenuEvent; FOCUS_EVENT_RECORD FocusEvent; } Event; } INPUT_RECORD;
In C++ and high level programming unions are probably very rarely used if ever.
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.