I'm facing situations where i'm finding it handy to store the type (as an enum) of an object in the base class to further cast a pointer to that base class into a subclass pointer depending on the value of that type.
For example :
class CToken
{
public:
token_type_e eType;
};
class COperatorToken : public CToken
{
public:
// Sub class specific stuff
};
class CLiteralToken : public CToken
{
public:
// Sub class specific stuff
};
And then
vector<CToken *> aTokens;
//...
for( size_t nI = 0, nMaxI = aTokens.size(); nI < nMaxI; ++nI )
{
switch( aTokens[ nI ]->eType )
{
case E_OPERATOR :
// Do something with sub-class specific stuff.
break;
case E_LITERAL :
// Do something with sub-class specific stuff.
break;
}
}
Is it a bad practice ?
Thank you :)
EDIT:
Say i'm analyzing my token list. At some point i'll want to check if the current token is an operator using, as people suggest, a virtual function virtual bool isOperator()
.
Now if it IS an operator, i will want to access that sub class specific stuff to find out, for example, which type of operator it is. In that case, what can i do ? I can't add a method getOperatorType() in my base class, that wouldn't make sense. Is there another way than casting to subclass to retrieve that sub class member value ?