You should not be casting from random types to pointer types. Even though casting char const *
, int
, and bool
appear to work for you, they are not any more what you want than casting float to a pointer. In fact you should view any cast in C++ as a warning sign that you may be doing something incorrectly.
Instead you should do something like the following.
class thing {
private:
union {
char const *cs;
int i;
bool b;
float f;
};
enum class type { cs, i, b, f } stored_type;
public:
thing(const char* x) : cs(x), stored_type(type::cs) {}
thing(int x) : i(x), stored_type(type:: i) {}
thing(bool x) : b(x), stored_type(type:: b) {}
thing(float x) : f(x), stored_type(type:: f) {}
void print()
{
switch(stored_type)
{
case type::cs:
std::printf("%s\n", cs); break;
case type::i:
std::printf("%i\n", i); break;
case type::b:
std::printf("%s\n", b ? "true" : "false"); break;
case type::f:
std::printf("%f\n", f); break;
}
}
};
Or better yet you could use a library that already does this for you, such as boost::variant, or boost::any.