Consider the three code blocks below, three alternative solutions to the string/union conflict.
Of these options, in general, which is more memory efficient regarding the use of unions in this fashion?
I'm looking for answers addressing principle here: that is, the primary purpose of unions is to save memory.
EDIT: A class assignment forced me to use unions in this way. It had me thinking which was the most efficient, and that's how I got here.
Code Block (A):
// unions with pointers to structs
struct HourlyInfo {
string firstName;
string lastName;
string title;
int hoursWorked;
double hourlyRate;
};
struct SalaryInfo {
string firstName;
string lastName;
string title;
double salary;
double bonus;
};
struct Employee {
bool isHourly;
union {
HourlyInfo *hourlyEmployee;
SalaryInfo *salaryEmployee;
}
};
Code Block (B):
// applying unions to relevant and non-string data types
struct Employee {
string firstName;
string lastName;
string title;
bool isHourly;
union {
struct {
double hourlyRate;
int hoursWorked;
} hourly;
struct {
double salary;
double bonus;
} salaried;
};
};
Code Block (C):
// use cstring instead of string
struct HourlyInfo {
cstring firstName[50];
cstring lastName[50];
string title[50];
int hoursWorked;
double hourlyRate;
};
struct SalaryInfo {
cstring firstName[50];
cstring lastName[50];
cstring title[50];
double salary;
double bonus;
};
struct Employee {
bool isHourly;
union {
HourlyInfo hourlyEmployee;
SalaryInfo salaryEmployee;
}
};
(Note: The idea behind the code is that any employee is either hourly or salary, thus the union here. Please don't suggest alternative solutions to this problem that do not involve unions. I'm not worried about solving a specific problem, I'm interested in unions.)
Also, pointers and other data types seem to vary greatly in their sizes:
What does the C++ standard state the size of int, long type to be?
How much memory does a C++ pointer use?
Does this mean there is no blanket statement we can make about memory efficiency here? If so, which factors should we consider in determining most-efficient methods?