struct or class object with constructor in UNION flags as error. !!

I

iceColdFire

Hi @all,

I am trying to include struct and class objects in a union ,like
class A{
int a;
A(){}
};

struct B
{
int b;
B(){}
};

union U
{
A ao;
B bo;
int i;
char r;
};

However, the above construction is flagged as error, now if I remove
the constructors from the above class and struct , the error is no
more....
I need some explanation , as why is this happening ...
Is it possible that somehow constructors change the way an object is
represented in memory...

Thank,
a.a.cpp
 
K

Krishanu Debnath

iceColdFire said:
Hi @all,

I am trying to include struct and class objects in a union ,like
class A{
int a;
A(){}
};

struct B
{
int b;
B(){}
};

union U
{
A ao;
B bo;
int i;
char r;
};

However, the above construction is flagged as error, now if I remove
the constructors from the above class and struct , the error is no
more....

It is error because Class A(and B) has non-trivial constructor. Sec 5.9
[class.union], para 1 puts this restriction. Here is the quote from
standard ..

"An object of a class with a non-trivial constructor (class.ctor), a
non-trivial copy constructor (class.copy), a non-trivial destructor
(class.dtor), or a non-trivial copy assignment operator (over.ass,
class.copy) cannot be a member of a union, nor can an array of such
objects."

Krishanu
 
I

iceColdFire

Hi :: Krishanu,

Indeed your pasted excerpt from the standard was very helpful to clear
up the things...
My problem has been solved...however C++ specific technical
specification of why is this not allowed shall be appreciated....

Perhaps, the current problem is solved by your answer.

Thanks,
a.a.cpp
 
J

John Carson

iceColdFire said:
Hi :: Krishanu,

Indeed your pasted excerpt from the standard was very helpful to clear
up the things...
My problem has been solved...however C++ specific technical
specification of why is this not allowed shall be appreciated....

The constructors you gave for A and B don't actually do anything, so your
code committed a "technical breach" only of the standard. But suppose that
they did something and the two things were in conflict, e.g., suppose A's
constructor sets the value of its integer member a to 5 and B's constructor
sets the value of its integer member b to 7. The integer members a and b
occupy the same memory in the union and plainly the constructors are in
conflict so at least one of the objects cannot be properly constructed.
 
I

iceColdFire

::John

Nice explanation ...things are getting clearer technically ....

+Thanks
a.a.cpp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top