Narek
Narek

Reputation: 39881

C++ union usage to store case specific data

Say I store data for a person. And depending it is a male or female gender specific data will be stored as well. Now should I use Union to store that gender specific part? Is it a good practice or there is a better way, especially using C++14?

Upvotes: 0

Views: 105

Answers (2)

phuclv
phuclv

Reputation: 41952

You can declare an unnamed union inside the class

class Person
{
    int gender;
    // common stuff, which is empty in your case
    int age;
    int height;

    union {
        struct {
            // female specific stuff
            // ???
        } female;

        struct {
            // male specific stuff
            // ???
        } male;
    }
};

Then uses things like

Person p;
switch (p.gender)
{
case MALE:
    p.male.some_attribute = somevalue;
    break;
case FEMALE:
    p.female.some_attribute = somevalue;
    break;
}

You can even remove the structs' names if there's no common property name between male and female so you only need to use p.some_male_attribute or p.some_female_attribute directly without another dot.

Upvotes: 1

trenki
trenki

Reputation: 7363

Union only works with basic types not with classes. You could not have a std::string in your union. Therefore union is rarely used in C++ but more often used in C.

In your case I would keep it simple. The simplest way is to just have all the data members in the same class regardless of gender and simply only use the right ones.

class Person
{
   // common stuff
   int age;
   int height;

   // female specific stuff
   // ???

   // male specific stuff
   // ???
};

Alternatively you could use inheritance like so:

class Person {};
class FemalePerson : public Person {};
class MalePerson : public Person {};

And have the gender specific part only in the corresponding derived class.

Upvotes: 3

Related Questions