Defined:
union is a user-defined type in which all members share the same memory location. " > union is a user-defined type, where all members share the same memory location. This means that at any given time, a union cannot contain multiple objects from its member list.
That is, the Union saves only the last member that was written. When the new value is assigned, the old value is flushed.
So be careful, because it's up to you to be responsible for ensuring that the last member that is written is always accessed.
A Union cannot store references. unions do not support inheritance, so the Union itself cannot be used as a base class, inherited from another class, or has a virtual function.
A Union can have member functions.
benefits:
And it can change its value at any time, and these values are of different types.
Statement:
Union [name] {member-list};
Example:
Declaring_a_union.cppunion recordtype //Declare A simple Union type{ char ch; int i; Long l; float F; Double D; int *int_ptr;}; int main () { recordtype t; T.I = 5; T holds an int T.F = 7.25//t now holds a float}
Unrestricted Union (C++11)
In C++03 and earlier, a union can contain a non-static data member (Class) with a class type, as long as the type does not have a user-supplied constructor, destructor, or assignment operator.
In c++11, these limitations are eliminated. If you include such a member in a union, the compiler automatically marks any special member functions that are not provided by the user as deleted. If the union is an anonymous union in a class or struct, any special member functions of the class or struct that are not provided by the user are marked as deleted.
Anonymous union:
Union { member-list }
Names declared in an anonymous union can be used directly, just like non-member variables. Therefore, the names declared in the anonymous Union must be unique within the perimeter scope.
union Member Data, anonymous unions is subject to Addit ional restrictions: "> In addition to the restrictions listed in federated member data, Anonymous federation is subject to other restrictions:
-
If you declare a union within the scope of a file or namespace, you must also declare them as "static."
They can have only public members; private members and protected members in an anonymous union generate an error.
They cannot have function members.
Union----Union