difference between struct and union

can someone explain to me what is the difference between a struct and union in c++?

i have read some explanation but i need an explanation in lay mans term. please...
The main difference is the way they store things in memory.

A struct will allocate space in memory for each of it's members.

A union will use the same space in memory for each of it's members.
Make a list of (primitive) objects; int, double, etc.

A struct can contain all of those objects at the same time.

A union will contain any one object at any one time. Making sure that it contains the right object at the right time is up to you. In C, it was commonly used as a neat means of polymorphism. In C++, we've got better ways to do it.
Last edited on
closed account (z05DSL3A)
structs are functionally identical to classes only with the default access level for its members are public.

unions are similar to classes only they can hold a value for only one data member at a time. other differences are:
~ like structs, the default access level is public.
~ they can not have virtual members.
~ they can not inherit or be inherited from.
~ members cannot be objects that define constructors, destructors, or overload the assignment operator.

Topic archived. No new replies allowed.