Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set union in class initializer?

Given a class such as the one below and the given union, how does one initialize the union to the correct value?

What is being attempted here is to use two or more different types as one of the core data types for the class. Instead of using void*, given that the types are known ahead of time a union of the types that are going to be used is constructed. The problem is how to initialize the correct union member when the class is instantiated. The types are not polymorphic, so the usual inheritance model did not seem appropriate. Some naive attempts to initialize the correct union member led nowhere.

union Union {
   int n;
   char *sz;
};

class Class {
   public:
   Class( int n ): d( 1.0 ), u( n ) {}
   Class( char *sz ): d( 2.0 ), u( sz ) {}
   ....
   double d;
   Union u;
};

After scouring for a solution, an answer became obvious, and could possibly be a good solution for this repository of answers, so I include it below.

like image 693
glenng Avatar asked Mar 11 '11 02:03

glenng


People also ask

How do you initialize a union?

An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).

Can we initialize union in C?

In C99, you can use a designated union initializer: union { char birthday[9]; int age; float weight; } people = { . age = 14 }; In C++, unions can have constructors.

How many union members can be initialize?

A union can be initialized on its declaration. Because only one member can be used at a time, only one can be initialized. To avoid confusion, only the first member of the union can be initialized.


1 Answers

For any type that does not have a constructor, it turns out that you can initialized it in a union. This answer on union initializers gives a hint to the solution:

union Union {
   int n;
   char *sz;
   Union( int n ): n( n ) {}
   Union( char *sz ): sz( sz ) {}
};

Now it works as expected. Obvious, if you knew what to look for.

Edit: You can also note the type used in the union in your class constructor, typically with an int or the like.

like image 190
glenng Avatar answered Sep 21 '22 16:09

glenng