union can't contain an object that has a virtual function

c++, unions

Solution

The implicitly declared default constructor, copy constructor, and copy assignment operator for that struct are non-trivial because it has a `virtual` function, so you've broken those requirements.

A constructor is trivial if it is an implicitly-declared default constructor and if:

- its class has no virtual functions (10.3) and no virtual base classes (10.1), and

- [...]

A copy constructor for class `X` is trivial if it is implicitly declared and if

- class `X` has no virtual functions (10.3) and no virtual base classes (10.1), and

- [...]

A copy assignment operator for class `X` is trivial if it is implicitly declared and if

- class `X` has no virtual functions (10.3) and no virtual base classes (10.1), and

- [...]

The C++11 quote is similar (it just includes move constructors and assignment operators) but C++11 does not have the same requirement on members of unions.

Problem

Code: ``` struct A{ int a; virtual void f(){} }; union B{ A ob; }; ``` Compile-time Error: ``` C:\to\main.cpp|9|error: member 'A B::ob' with constructor not allowed in union| C:\to\main.cpp|9|error: member 'A B::ob' with copy assignment operator not allowed in union| ||=== Build finished: 2 errors, 0 warnings ===| ``` c++03 Standard: An object of a class with a non-trivial constructor (12.1), a non-trivial copy constructor (12.8), a non-trivial destructor (12.4), or a non-trivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects. If a union contains a static data member, or a member of reference type, the program is ill-formed. The standard doesn't say anything about an object of a class with a virtual function, and from the error, the compiler complain about constructor and copy-assignment operator which I didn't use. so is this a compiler bug ? Im using gcc .

Original source