string inside Union

Mar 12, 2009 at 4:40am
Hi Guys,

Can't we have string inside unions?
When I try to use

1
2
3
4
5
6
7
class A {
public:
string str;
}; 
union { 
A obj; 
}p; 


It keep saying that
<anonymous union>::’ with constructor not allowed in union

Any thoughts ?

Last edited on Mar 12, 2009 at 4:41am
Mar 12, 2009 at 4:46am
Members of union cannot have a copy constructor.
Mar 12, 2009 at 5:00am
is there any work around for that?

Mar 12, 2009 at 7:56am
Maybe there is a better solution without using unions. What do you want to do?

The only "work around" would be to use an char array or an pointer to a string. But it would be very dangerous if you used that pointer if it's actually something else...

EDIT: typo
Last edited on Mar 12, 2009 at 7:56am
Mar 12, 2009 at 10:55am
@onur
Yeah man, I was using pointer before but then I had to switch to strings. And now my code is full of strings in almost every class. Finally, I ended up using char * instead of unions. And storing my data in that pointer using memcpy.

Thanks for the reply thou guys.
Mar 12, 2009 at 12:25pm
boost::variant is the workaround.
Mar 12, 2009 at 4:32pm
you can use a struct if thats feasible, union cant work with string class.
i think no class object will go inside a union because even if you dont define a copy const/assignment opt, compiler will do that for you.
Mar 12, 2009 at 11:36pm

i think no class object will go inside a union because even if you dont define a copy const/assignment opt, compiler will do that for you.


That's the weird thing dude, it allows to include class object inside a union BUT an object which contains a string data member
Topic archived. No new replies allowed.