Reputation: 6686
I have the code:
class Vector4
{
public:
union
{
float x,y,z,w;
float v[4];
};
Vector4(float _x, float _y, float _z, float _w)
: x(_x), y(_y), z(_z), w(_w)
{
std::cout << "Vector4 constructor: " << this->x << "; " << this->y << "; " << this->z << "; " << this->w << std::endl;
}
};
As I remember in VC 7.1 everything was fine, but in VC 2010 I got warning:
warning C4608: 'Vector4::y' has already been initialized by another union member in the initializer list, 'Vector4::::Vector4::x'
And when I write:
Vector4 vec(1.0f, 0.0f, 0.0f, 0.0f);
I see in console:
Vector4 constructor: 0; 0; 0; 0
Please tell me, what happening?
Upvotes: 2
Views: 953
Reputation: 179392
You unioned x,y,z,w
all to each other: all four floats share the same memory space since every element of a union begins at the same memory address.
Instead, you want to put all of the vector elements in a struct, like this:
union {
struct { float x, y, z, w; };
float v[4];
};
Upvotes: 10