string inside Union

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
Members of union cannot have a copy constructor.
is there any work around for that?

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
@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.
boost::variant is the workaround.
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.

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.