Unions in C++

Started by
30 comments, last by sab3156 20 years ago
What the hell is the point of using Unions? Can anybody write some example code? I don''t really get it. Also, is it true that the members of the Union are stored in the same memory location? That REALLY bugs me.
Air-Conditioners are like computers. They stop working when you open windows.
Advertisement

  class Vector{public:   union   {      struct { float x, y, z; };      float v[3];   };// blablablabla}  


Yes, I know it can cause problems to use anon structs, but it was the first thing that came to my mind and it works on the compilers I use.
OH ok! can u show me another exampl? im starting to get it. woohoo.

[edited by - sab3156 on December 27, 2002 12:43:03 PM]
Air-Conditioners are like computers. They stop working when you open windows.
Yes, they are stored in the same memory location.

Here''s some example code from my class ''Vector'':


  union VectorUnion{    struct VectorStruct    {        float	x;        float	y;        float	z;        float	w;    }v;    float		vector[4];}t;  


To clear up code I use the x,y,z... values in my functions. But sometimes I need the array, for example when passing the vector to a OpenGL function like glVertex4f.

Without the union I''d have to copy data from the variables to the array and vice verca each time one of ''em changed. This way I don''t.
How do I set my laser printer on stun?
so how would you use the vector[4] variable?
Air-Conditioners are like computers. They stop working when you open windows.
This is the default constructor of my class. If you know how to work with structs this should be familiar.


  Vector::Vector(void){	t.v.x=0;	t.v.y=0;	t.v.z=0;	t.v.w=0;}  


Now, instead of writing

t.v.x=0;

you could also write

t.vector[0]=0;

It''s simply:

''x == vector[0]''
''y == vector[1]''
''z == vector[2]''
''w == vector[3]''
How do I set my laser printer on stun?
oh ok. nice. thanks.
Air-Conditioners are like computers. They stop working when you open windows.

You should use initializer lists in constructors as often as possible; especially for a small, often used class like this:

Vector::Vector(void) :
t.v.x ( 0 ),
t.v.y ( 0 ),
t.v.z ( 0 ),
t.v.w ( 1 )
{
}
What's the advantage, except for making it look more cryptic?
I've never heard of initializing members of a struct that way.

edit: Didn't work...

[edited by - Wildfire on December 27, 2002 1:34:03 PM]
How do I set my laser printer on stun?
quote:Original post by Wildfire
What''s the advantage, except for making it look more cryptic?
I''ve never heard of initializing members of a struct that way.


Then you should read the C++ FAQ Lite.

This topic is closed to new replies.

Advertisement