Unions

Since unions occupy the same address space, what happens when you have something like...
1
2
3
4
5
union unionTest{
bool tF; //1 byte
char alpha; //1 byte
int num; //4 byte
};


What happens in this scenario? In all the scenarios, there would of been an array of 4 for tF and alpha to match up with num, but in this scenario, what happens?
Last edited on
An array of 4? I don't understand.

You'd just have this:

[b][ ][ ][ ]
[c][ ][ ][ ]
[i][i][i][i]


There is no array.
You haven't declared a union. You need the union keyword for that (not struct).

With a union, the compiler set aside enough space for the largest member.
In unions, the members share the same space. Unions are useful for defining some kind of abstract data type.
1
2
3
4
5
6
7
union shared_data
{
    char character;
    bool boolean;
    int integer;
    float decimal;
};


For differently-sized members, the union takes the size of the largest member.
Union's members may not have some sort of constructor. They must be C-style POD.
Structures may also be a member of union.
Last edited on
Unions' members may not have some sort of constructor. They must be C-style POD.


This article is about C++11 unions

http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=556


One observation is that there are a lot of new things in C++11.
@firedraco
In the example in the tutorials, they had an array of 4, which is created "int arrayTest[4];".

That was what I was looking for. I wanted to know how it would look like if first two data types were smaller than the last. Thanks for explaining this.
Topic archived. No new replies allowed.