How to dynamically create an instance of union in C ++?

I need to have multiple union instances as class variables, so how can I create a union instance on the heap? thanks

+4
source share
6 answers

Same as when 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 join is the size of the largest data member.

+7
source

My C ++ is a little rusty, but:

  my_union_type *my_union = new my_union_type; ... delete my_union; 
+2
source

Use the new operator.

0
source

Same as struct :) You can use malloc() and do it the way C, or new for C ++. The secret is that structures, unions and classes are interconnected; struct is just a class (usually) with no methods. Where there is further clarification in the following comments, you should take care.

0
source

I'm not sure where you want to handle this. A union is user-defined data or a class type that at any given time contains only one object from its list. So, starting from this, if you have an alliance defined as follows:

 union DataType { char ch; integer i; float f; double d; }; 

You can then use the DataType as a type for defining members in a class, or as a type for defining variables in a stack, like regular types, structures, or classes that you define.

0
source

Use the new operator:

 #include <iostream> union u { int a; char b; float c; }; class c { public: c() { u1 = new u; u2 = new u; u3 = new u; } ~c() { delete u1; delete u2; delete u3; } u *u1; u *u2; u *u3; }; int main() { c *p = new c; p->u1->a = 1; p->u2->b = '0' + 2; p->u3->c = 3.3; std::cout << p->u1->a << '\n' << p->u2->b << '\n' << p->u3->c << std::endl; delete c; return 0; } 
0
source

All Articles