For the following code:
class Foo{
int foo;
public:
Foo() : foo(13) {}
int getFoo() const { return foo; }
};
union Bar{
Foo fBar;
double dBar;
};
I believe this is fully legal in C++. http://en.cppreference.com/w/cpp/language/union#Explanation says:
If two union members are standard-layout types, it's well-defined to examine their common subsequence on any compiler
And thus in gcc I can do this:
Bar bar = { Foo() }
When I try this in Visual Studio 2008 I get the error:
error C2620: member
Bar::fBar
ofunion Bar
has user-defined constructor or non-trivial default constructor
Error C2620 states:
A union member cannot have a default constructor.
What's going on here? Was this ever a C++ requirement, I thought that Standard Layout was the only requirement? Is there a work around for this?