Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically create a union instance in c++?

I need to have several instances of a union as class variables, so how can I create a union instance in the heap? thank you

like image 434
derrdji Avatar asked Dec 29 '22 10:12

derrdji


2 Answers

The same as creating any other object:

union MyUnion
{
   unsigned char charValue[5];
   unsigned int  intValue;
};


MyUnion *myUnion = new MyUnion;

Your union is now on the heap. Note that a union is the size of it's largest data member.

like image 140
RC. Avatar answered Jan 13 '23 13:01

RC.


My C++ is a bit rusty, but:

   my_union_type *my_union = new my_union_type;
   ...
   delete my_union;
like image 38
Frank Schmitt Avatar answered Jan 13 '23 15:01

Frank Schmitt