GAP
GAP

Reputation: 395

Can union contain objects of a class with user define constructor?

Can union contain objects of a class with user define constructor? When i try to create a it gives an error saying " member 'c::aa' of union 'c' has user-defined constructor or non-trivial default constructor" Is it a standard or is there any mistake in my code?

The code i tested is

class a
{  
public:

  int aaa;
  a(){}

};

class b
{

public :

  long bbb;
  b() { }

};

union c
{

public :

  c()  {}

    a aa;
  b bb;  
};

Upvotes: 1

Views: 3655

Answers (3)

Brian A. Henning
Brian A. Henning

Reputation: 1511

Prior to C++11, the answer is "no"--a union can only contain value types (to borrow a term from managed code), that is, a type that only contains data members.

Unions share their memory footprint across all members. Having complex members in a union would result in a situation where methods acting on data members of one class would clobber data members of the other class in the union.

Perhaps what you want is a struct.

Upvotes: 2

shawn1874
shawn1874

Reputation: 1435

class a
{  
public:

  int aaa;
  a(){}

};

class b
{

public :

  long bbb;
  b() { }

};

union c
{

public :

  c()  {}

    a aa;
  b bb;  
};

int main()
{
    return 0;
}

The above code worked fine using the following online compiler. http://www.compileonline.com/compile_cpp11_online.php

So the answer is yes and no, depending on your compiler. MS VS 2010 does not compile that code because it is not yet fully C++11. Evidently the latest C++11 GCC compiler will compile it just fine! This is great in my mind, because all along the trivial user defined constructor simply initializes data and it does not change the memory layout.

The C++ 03 standard states that any class or struct with a user defined constructor is non-POD. Bjarn Stroustrup wrote something about that on his home page indicating that was too strict of a definition for POD vs. non-POD because user defined functions don't always cause a non-trivial memory layout. That is why the rule was relaxed.

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 477000

This is possible since C++11 ("unconstrained unions").

Upvotes: 2

Related Questions