In a nutshell: don't do it.
Unions are really best used when representing data that has the same binary representation, e.g.:
union v4f {
float f[4];
struct {
float x;
float y;
float z;
float t;
};
};
v4f v;
v.f[1] = 2.f;
v.t = 0.f;
Assuming you do actually want to use a union here, and not a struct, i.e. a token contains a name OR a literal, but never both at the same time, and you really need to save on the extra storage that a using struct would cost:
Before C++11, you couldn't have a union member with a non=trivial destructor, such as your tester.name
string field. See this question for more details.
Now, this is possible, although I would recommend not doing it unless you really know what's going on. To do that, you need to define your union's destructor, because it the compiler cannot decide which, if any of the non-trivial union members to delete. I think you are better off avoiding this, because this is not an easy question to answer, without any additional information:
~tester() {
// delete name member or not ?
// very hard to decide without additional data
}
As for how to access your union member, since your union is not anonymous, it can't be accessed anonymously, so you need to actually create a member of your class with this union type, and refer to that class member.
class Token {
public:
union tester {
double literal;
string name;
tester(double op) : literal(op) {};
tester(string val) : name(val) {};
tester(): tester(0.0) {};
~tester() {}
};
tester data;
...
};
...
Token t;
t.data.name = "Elly";