I would like to know the difference between structure and union for one member data type if there is any.
A structure can store multiple values of the different members. A structure's total size is the sum of the size of every data member. A union's total size is the size of the largest data member. Users can access or retrieve any member at a time.
Neither a structure nor union member can have a function type or an incomplete type. Structures and unions cannot contain instances of themselves as members, but they can have pointers to instances of themselves as members. The declaration of a structure with no members is accepted; its size is zero.
If you want to use same memory location for two or more members, union is the best for that. Unions are similar to the structure. Union variables are created in same manner as structure variables. The keyword “union” is used to define unions in C language.
The concept of structure and union are same. Both are created to collect different data type in one variable. The only difference is in memory management i.e. Memory requirement of the two.
In C: None. The famous "space-saving joke" #define struct union
is almost not a joke.
In C++98: Unions can only have POD members, non-union classes can have arbitrary members.
In C++11: Unions can have arbitrary data members of object type (but not of reference type), but their use is more restricted that that of non-union classes. (Namely: a union cannot have virtual member functions, cannot be a base class and cannot have base classes.) Also, you have to write more code to make a one-member union work as opposed to a one-member non-union class, since you have to write constructors and the destructor yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With