Unions in C++
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.
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]
[edited by - sab3156 on December 27, 2002 12:43:03 PM]
Yes, they are stored in the same memory location.
Here''s some example code from my class ''Vector'':
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.
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.
This is the default constructor of my class. If you know how to work with structs this should be familiar.
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]''
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]''
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]
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]
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
Popular Topics
Advertisement