What is the difference between a Union and a data structure in c++?

I honestly see little difference between the two. Data structures are types and variables grouped together under a single name and each member type of the structure can be used independently with the variable/object that was declared right after the structure.

But isn't a union basically the same thing? except the objects can somewhat be used as types?
The variables in Structs have their own individual memory for each variable.

A union has a united memory locations for ALL it's variables.

Think of it in Processor Architecture terms..

The Accumulator can be seen as:

A 32bit register
A 16bit register
2 8bit registers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct vars // Each variable has it's own memory, using one will not modify the other
{
int a;
short b;
char[2] c;
};

union Register // Union - Each var access the same location in memory
{
int a;
short b;
char[2] c;
} EAX;
Unions are somewhat different. Objects they group share same memory place. Only one of them can be used at a time without causing an UB.

example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
union foo
{
    int i;
    char c[4];
    double d;
    int* p;
};

int main()
{
    foo bar;
    bar.i = 9000; //i is now active
    bar.d = 10.5; //i is inactive, d is active
    //i value was overwritten by d value.
    //↓UB!↓ You should not access non-active members
    //std::cout << bar.i;

    //As you can see, size of union is less than size of all its members
    std::cout << sizeof(foo) << '\n' << 
                 sizeof(foo::i) + sizeof(foo::c) + sizeof(foo::d) + sizeof(foo::p);
}
8
24
I see, so do you think data structures are more useful than unions? I say this since I'm having a bit of trouble trying to add a std::string member to the union


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct data
{
    int numberInt;
    float numberFloat;
    char symbolChar;
    std::string sentenceString;

}; data number, symbol, sentence, arrayData[5];

union united
{
        float numberFloat1;
        int numberInt1;
        std::string string1;

} library;



The compiler doesn't show any errors when I remove the string member from the union , but can unions even have strings as their members? or does the union have to have all of its members be of the string class in order to use strings?
Last edited on
I see, so do you think data structures are more useful than unions?
unions and classes are different. And have different uses. Generally if you do not have solid understanding of what union is, you shouldn't use it.

can unions even have strings as their members?
No. Union can only have members of trivial types. This is because non-trivial classes usually have invariants which would be wrecked as soon as some other member in union would be assigned.
Topic archived. No new replies allowed.