6

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 .

timrau
  • 22,578
  • 4
  • 51
  • 64
AlexDan
  • 3,203
  • 7
  • 30
  • 46
  • By non-trivial, think POD (http://en.wikipedia.org/wiki/Plain_old_data_structure) – Benj Feb 19 '13 at 17:12
  • @Benj I dont know what non-trivial mean, but im sure it's not POD since it A can have a base class, in this I dont get an Error, so union member data doesn't have to be a POD. – AlexDan Feb 19 '13 at 17:16
  • If you check out the article I referenced you'll see that unions are mentioned specifically with regard to POD. Also it's possible for a class to be POD. – Benj Feb 19 '13 at 18:34

2 Answers2

11

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.

Community
  • 1
  • 1
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
0

Use C++11 if you can, it doesn't contain such constraint

ixSci
  • 13,100
  • 5
  • 45
  • 79