You declared unnamed global union named mycolor, not a new union type called mycolor.
This is one of the reasons it won't compile.
A new union type named mycolor would be:
union mycolor{
Uint32 rgba;
sf::Color sfcolor;
};
Also, this is quite an artificial problem, no wants to put sf::Color and sf::Uint32 into an union like you shown, we only intend to add the new constructor.
And actually, an union containing sf::Color will not compile, in C++98 it has a constructor which is forbidden, in C++11 (which relaxed the rules) it has non trivial constructor so it won't compile either.
IF you mean that this byte packing doesn't work on big endian then you are not right either, look:
#include <cstdio>
#define rf 0xff000000
#define gf 0x00ff0000
#define bf 0x0000ff00
#define af 0x000000ff
typedef unsigned char u8;
typedef unsigned u32;
class Color
{
public:
Color(u8 r, u8 g, u8 b, u8 a = 255):
r(r), g(g), b(b), a(a) {}
Color(u32 col):
r((col & rf) >> 24), g((col & gf) >> 16), b((col & bf) >> 8), a(col & af) {}
u8 r, g, b, a;
};
int lilend()
{
int i = 1;
return (*(char *)&i) == 1;
}
void printcol(Color c)
{
std::printf("r = %x, g = %x, b = %x, a = %x\n", c.r, c.g, c.b, c.a);
}
int main()
{
std::printf("endian lil = %d\n", lilend());
std::printf("sizeof u32 = %d sizeof u8 = %d\n", sizeof(u32), sizeof(u8));
Color c(0x00ff00ff);
std::printf("next line is 0, ff, 0, ff\n");
printcol(c);
c.r = 255;
c.g = 0;
std::printf("next line is ff, 0, 0, ff\n");
printcol(c);
}
I ran this code on few machines (since I can't get full SFML there, we use equivalent code like one we intend to use in sf::Color).
This is from an old machine running 32 bit (at least I think so because size of pointer is 4) Sun-OS 5.10 on big endian CPU (it's sparc I think, not sure now, but definitely big endian...).
endian lil = 0
sizeof u32 = 4 sizeof u8 = 1
next line is 0, ff, 0, ff
r = 0, g = ff, b = 0, a = ff
next line is ff, 0, 0, ff
r = ff, g = 0, b = 0, a = ff
This is from my local machine, which is obviously standard Intel CPU, 64 bit capable but running 32 bit Fedora 20 with little endian.
endian lil = 1
sizeof u32 = 4 sizeof u8 = 1
next line is 0, ff, 0, ff
r = 0, g = ff, b = 0, a = ff
next line is ff, 0, 0, ff
r = ff, g = 0, b = 0, a = ff
I by mistake ran it on a multicore FreeBSD on AMD64 (also little endian) and result was same as on my machine.
As you see, endian and bitness doesn't affect this kind of thing, the constructor itself works as intended, we can use the color normally, etc. and unions are non issue, since sf::Color can't be put in one anyway.