So I am trying to write a simple interpreter in c++, but ran into some problems. I have a Token class, which holds an enum TokenType, and a TokenValue object. The TokenValue class is the base class of several other classes (TV_String, TV_Int, and TV_Float).
Here is the code for the TokenValue and its children classes:
// TokenValue.h
class TokenValue
{
public:
void* value = NULL;
virtual bool operator ==(const TokenValue& tv) const
{
return typeid(this) == typeid(tv) && value == tv.value;
}
};
class TV_Empty : public TokenValue {};
class TV_String : public TokenValue
{
public:
std::string value;
TV_String(std::string value); // The constructors just assign the value argument to the value field
};
class TV_Int : public TokenValue
{
public:
int value;
TV_Int(int value);
};
class TV_Float : public TokenValue
{
public:
float value;
TV_Float(float value);
};
Here's the code for Token:
// Token.h
class Token
{
public:
enum class TokenType
{
// all the different types
}
TokenType type;
TokenValue value;
Token(TokenType type, TokenValue value); // just initialises type and value, nothing else
}
The problem I am having is that the value field is not being changed when I use any of the children classes (it always shows 00000000 when I print it, I assume that's the value of void* value = NULL, but not sure). From research I think it could be solved by using templates, but in my case I can't use templates because Token never know the type of its corresponding TokenValue.
So how can I override the type and value of the value field and access the correct value in the children classes, and in the == operator?
(Thanks to Jarod42 I realised it doesn't "override" the field, it creates a new field with a different type and the same name.)