Union cannot contain an object that has a virtual function

The 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:

A class object with a nontrivial constructor (12.1), a nontrivial copy constructor (12.8), a nontrivial destructor (12.4), or a nontrivial copy assignment operator (13.5.3, 12.8) cannot be a member of a union, nor can an array of such objects. If the union contains a static data element or a member of a reference type, the program is poorly formed.

The standard does not say anything about a class object with a virtual function, and from an error, the compiler complains about the constructor and copy operator, which I did not use. so is this a compiler error? Im using gcc.

+5
source share
2 answers

, , virtual, .

, :

  • (10.3) (10.1)
  • [...]

X ,

  • class X (10.3) (10.1)
  • [...]

X ,

  • class X (10.3) (10.1)
  • [...]

++ 11 ( ), ++ 11 .

+10

++ 11, ,

0

All Articles