Unions and Structs

What is the difference between an Union and a Struct?
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
So with unions we can have a variable type?
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
But how will a char hold the value of an int?
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.
Thanks, that explains it!!!
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
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. ;)
^Unions can't have virtual functions.
^^Valid only when the union is not anonymous.
Well you can't inherit from an unnamed union :p
Last edited on
You can inherit from the struct/class the unnamed union is in...
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
Last edited on
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.