Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stuff a class with user-defined constructors into a union

class Foo {
    Foo(int val) { /* Do some initialization */ }
    Foo() { /* Do nothing */ }
};
union Bar {
    Foo foo;
};

That code generates this error:

error C2620: member 'Bar::foo' of union 'Bar' has user-defined constructor or non-trivial default constructor

I understand why you'd throw that error if the constructor actually did something, but the constructor here takes no parameters and does nothing. Is there any way I can stuff this class into a union? I've had to resort all the way to doing char foo[sizeof(Foo)] and would like a cleaner solution.

like image 889
Chris Avatar asked Dec 29 '22 07:12

Chris


1 Answers

Originally from this question:

Initializing a union with a non-trivial constructor:

From C++03, 9.5 Unions, pg 162

A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. A union shall not have base classes. A union shall not be used as a base class.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

So, your class is forbidden to be a member of the union.

like image 74
LaszloG Avatar answered Feb 02 '23 09:02

LaszloG