Here's conceptually-similar code: (part of code to render some 2D sprites on-screen)
struct Color
{
uint8_t r = 255;
uint8_t g = 255;
uint8_t b = 255;
uint8_t a = 255;
};
struct Vertex
{
Color color;
Other stuff;
};
union QuadCorners
{
struct { Vertex topLeft, topRight, bottomRight, bottomLeft; };
Vertex vertices[4]; //type-punning
};
And elsewhere in my code I save a copy of the current vertices for "settings".
struct Settings
{
QuadCorners corners;
Other stuff;
};
class Editor
{
public:
void PlaceNewQuad(vectpr4reals position)
{
Quad *newQuad = CreateNewQuad(position);
ApplySettingsToQuad(*newQuad);
}
void ApplySettingsToQuad(Quad &quad)
{
quad.corners = this->currentSettings.corners;
quad.corners = this->currentSettings.corners;
}
private:
Settings settings;
};
Well, for some reason, my colors were all gibberish. :P
[rollup="Explanation"]Color's member variables aren't being initialized because its constructor isn't getting called because it's in a union, and the union doesn't know whether to treat the union as the four 'Vertex' members in the anonymous struct or as an array of 4 elements of type Vertex.
This is a minor 'gotcha' and one I should've caught quickly, but two things distracted me:
A) The obvious 'no-no' with unions is that you can't write to one member and read from the other - but since I'm doing that intentionally for type-punning, I wasn't worried, and was distracted by the 'obvious' gotcha, that I forgot that the members wouldn't be initialized.
B) I was also doing funky pointer stuff on the vertices elsewhere, so I assumed that must've been the location that was mucking up the color values. :) [/rollup]
I only realized what was going on when I stepped through the code with the debugger and saw that Editor::settings started off with bad values.