Unions in C++ are special type of
classes. We can declare member functions and variables with in the
union in c++ (all 'C' features of union remain same).
But in the unions
all the data members share the same memory location.
Union members are public by default as
like structures.
Anonymous unions are the special type
unions with the no name and so we can not create object for that
union. All the member data in the anonymous unions share same memory
location. We can directly access the these members without any dot
operator with in the block where these unions declared.
The scope of
the anonymous union members restricted to the block where it declared
and these members can be treated as the local varibles to that block,
so there shouldn't be any conflict between the names of the variables
defined with in the unions and variables defined with in the block.
For example:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
union
{
int i;
char ch[4];
};
i = 56;
cout<<"i val: "<<i<<" ch val:"<<ch<<endl;
memcpy(ch,"1",sizeof(ch));
cout<<"i val: "<<i<<" ch val:"<<ch<<endl;
return 0;
}
Output:
i val: 56 ch val:8
i val: 49 ch val:1
Here union member data i and ch are
having same scope as the variables declared with in the main block.
Here i and ch share the same memory location so when we set ivalue ch
value is also same. Ascii values 48 to 57 represents 0 to 9 decimal
numbers.
Note: Alls the restrictions applicable
to the unions in c++ are also applicable to anonymous unions
No comments:
Post a Comment