PDA

View Full Version : C++ question?



vermarajeev
25th October 2006, 05:59
Hi guys,
Till now I have never implemented a union in my code and have rarely seen union used anywhere...Also I was just wondering under what situations we should use a structure and when we should use a union?

Any help will be highly appreciated.
Thankx

wysota
25th October 2006, 08:35
To be honest I have never seen a union in C++ (I have seen many in C).
A structure is used when you need to store more than one piece of data (like a record). A union is used when you need to store a piece of data which can be of different types (but you can only access one of the pieces), for example:


union {
int intvalue;
float floatvalue;
}
Then you can assign data to either intvalue or floatvalue, but not to both at once (the data will be overwritten if you do).

I think in C++ unions are rarely used because you can achieve the same in a much cleaner way - for example using inheritance.

stinos
25th October 2006, 12:17
A structure is a class with only public members. Shouldn't be too hard to figure out when to use that..
Unions on the other hand are aggregate quantities like structs, except that each element of the union has offset 0, and the total size of the union is only as large as is required to hold its largest member. Only one member of a union may be "active" at a time. (thank you, google)
Unions are indeed rarely used, but they do have very interesting applications, eg: http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=271&rl=1

jpn
25th October 2006, 12:32
A structure is a class with only public members. Shouldn't be too hard to figure out when to use that..
You can have private members in a struct as well. The difference is that struct members are public by default and class members are private by default.


Unions are indeed rarely used
They use unions in Qt, for example in QVariant and some container classes as well.. ;)

mcosta
25th October 2006, 14:30
Also I was just wondering under what situations we should use a structure and when we should use a union?


A union is a set of "memory sharing variables". In example



union myUnion
{
int iValue;
float fValue;
};

struct myStruct
{
int iValue;
float fValue;
};

myStruct myS;
myS.iValue = 1;
myS.fValue = 2.0;

myUnion myU;
myU.iValue = 1;
myU.fValue = 2.0;

cout << myS.iValue << " " << myS.fValue << endl;
cout << myU.iValue << " " << myU.fValue << endl;



print something like



1 2.0
<some_value> 2.0


this because when you assign value to myU.fValue you set memory area use by myU.iValue

Union are useful to share the same memory area amoung several variables.
In Example this function



void printSwappedByte(unsigned short _val)
{
union
{
unsigned short sV;
unsigned char cV[2];
};

sV = _val;
cout << (unsigned int) cV[1] << " " << (unsigned int) cV[0] << endl;
}


print val bytes in revers order;