this question might have been answered before, but after two days of searching I couldn't find a solution.
I made a stack class which stores __data
:
class __data
{
private:
void* __p;
__datatype __type;
public:
__data(void);
__data(int i);
__data(double d);
__data(char* s);
__data(void (*f)(Stack));
bool IsFunction(void);
bool IsInteger(void);
bool IsNumber(void);
bool IsString(void);
void* Get(void);
};
I created this class because the stack will be able to store strings, functions (pointers to functions), doubles and integers.
The problem is when I push an integer or double into the stack and then pop it and get the pointer to the data (void* Get(void)
) I'm debugging it by printing out it's value, therefore I basically have this:
void print(Stack s)
{
__data d = s.Pop();
if (d.IsNumber()) // BUG: never the number I pass to __data
std::cout << "IsNumber - " << *((double*)d.Get()) << std::endl;
else if (d.IsInteger()) // BUG: it always prints out 1
std::cout << "IsInteger - " << *((int*)d.Get()) << std::endl; //
else if (d.IsString())
std::cout << "IsString - " << (char*)d.Get() << std::endl;
else if (d.IsFunction())
{
std::cout << "IsFunction - " << d.Get() << std::endl;
((void (*)(Stack))d.Get())(s); // calls the function
}
}
I don't know what might be wrong, maybe it's the way I assign __p
(the pointer returned by Get()
), these are the __data
constructors for integer and double:
__data::__data(int i)
{
__type = _dt_integer;
__p = &i;
}
__data::__data(double d)
{
__type = _dt_number;
__p = &d;
}
So basically my problem is when I try to get the integer or double pointed by the returned void*
it either gives me a value of 1
(integer) or 2.13171e-314
(double).
Thank you for your time, and sorry if there's already an answer for this out there.
Edit:
I'll re-write the Stack class and use a union instead. This seems to be the best method to achieve my goal.