Unions and Structs

Jun 13, 2011 at 10:29am
What is the difference between an Union and a Struct?
Jun 13, 2011 at 11:34am
they are completely different

a struct defines a record with a bunch of fields that go together
an union defines a variable type which can contain only one of many types at a time

so the sizeof( aStruct ) is the sum of the sizeof() of all its fields
while sizeof( anUnion ) is the sizeof() its largest field

in the early C days before C++, unions could be made into a poor man's polymorphic object or an Any object

edit: I am simplifying a bit here as there are data alignment issues in the case of struct, but the general difference in sizeof() is correct
Last edited on Jun 13, 2011 at 11:35am
Jun 13, 2011 at 11:55am
So with unions we can have a variable type?
Jun 13, 2011 at 12:01pm
Variable..in the sense....
1
2
3
4
5
union x
{
    int foo;
    char bar;
};

If you put a number in x.foo
x.bar will give you the char corresponding to the number resulting from taking the first byte(generally) of the int.
&&
If you change x.bar
x.foo also changes.
Last edited on Jun 13, 2011 at 12:01pm
Jun 13, 2011 at 12:02pm
But how will a char hold the value of an int?
Jun 13, 2011 at 12:07pm
It can't. Not entirely. The int and the char occupy the same memory, but as the int is larger than the char (takes more memory), the char will only represent some part of the integer's representation in memory, as manasij said.
Jun 13, 2011 at 12:10pm
Thanks, that explains it!!!
Jun 13, 2011 at 12:19pm
in manasij7479's example, x can hold either a int foo or a char bar, not both

which one does it really hold?

it's up to you to keep track in some other part of the program - the compiler doesn't care!

if you do an x.foo, it will give you an int and if you do an x.bar, it will give a char at that memory location
Jun 13, 2011 at 3:45pm
Do note that a union can still have member functions, do inheritance and polymorphism, overload operators, etc. It's just exactly the same as a struct, but where the data members use the same memory. ;)
Jun 13, 2011 at 5:07pm
^Unions can't have virtual functions.
^^Valid only when the union is not anonymous.
Jun 13, 2011 at 6:19pm
Well you can't inherit from an unnamed union :p
Last edited on Jun 13, 2011 at 6:34pm
Jun 13, 2011 at 6:21pm
You can inherit from the struct/class the unnamed union is in...
Jun 13, 2011 at 6:35pm
I just tried it in Visual Studio, and it won't allow a member union to be nameless anyway. Virtual or not.
Last edited on Jun 13, 2011 at 6:36pm
Jun 13, 2011 at 7:25pm
Last edited on Jun 13, 2011 at 7:34pm
Jun 13, 2011 at 7:45pm
Yeah, sorry - I wasn't on top form earlier... I meant to say "It won't allow member functions of a nameless union. Virtual or not". I was typing fast earlier :X You are right of course :)
Topic archived. No new replies allowed.