Hi I wanted know the reasons of the following code
void main()
{
class test
{
public:
test(){}
int k;
};
class test1
{
public:
test1(){}
int k;
};
union Test
{
test t1;
test1 t2;
};
}
For the Above code it gives error "error C2620: union 'Test' : member 't1' has user-defined constructor or non-trivial default constructor"
class test
{
public:
//test(){}
int k;
};
class test1
{
public:
//test()1{};
int k;
};
union Test
{
test t1;
test1 t2;
};
For the Above, No Errors.
I wanted to know the Reasons.
Thank you in Advance. :)
The C++ standard puts certain restrictions on the types of data which can be placed inside of a union. In 9.5.1 the standard reads:
So your program doesn't work because you explicitly define a constructor, and therefore your object violates the non-trivial constructor restriction.
According to the C++ standard (§9.5.1, cited as well in other answers):
I first linked to the Wikipedia article about POD types which states:
and
The first sentence of the second paragraph might make you think C++ only allows POD types to be part of a union. This isn't exactly the case as it allows a class with private members to be part of a union:
The program above compiled with MSVC++ prints out:
In C++, unions may not contain classes with (non-trivial) constructors or destructors. This is because the compiler has no means of telling which constructor or destructor to use when a union instance is created or destroyed.