Is it a good design to store the type of the object in the base class as an enum? For example, consider the following hierarchy
Expr
--Unary
--Binary
--Const
----Int
----Float
How to represent the above hierarchy in C++, so that I can inspect the type of an object of a subclass.
enum ExprType {
Const, Binary, Unary
};
class Expr {
ExprType type;
public:
Expr(ExprType t) : type(t) { }
ExprType GetType() { return type; }
};
class BinNode: public Expr {
Expr* left, *right;
Operator op;
public:
BinNode() : Expr(ExprType::Binary) { }
};
class UnrNode: public Expr {
Expr* operand;
Operator op;
public:
UnrNode() : Expr(ExprType::Unary) { }
};
enum ConstNodeType {
Int, Float
};
class ConstNode: public Expr {
ConstNodeType cntype;
public:
ConstNode(ConstNodeType t) : Expr(ExprType::Const), cntype(t) { }
ConstNodeType GetConstType() { return cntype; }
};
class IntNode: public ConstNode {
int value;
public:
IntNode() : ConstNode(ConstNodeType::Int) { }
};
class FloatNode: public ConstNode {
float value;
public:
FloatNode() : ConstNode(ConstNodeType::Float) { }
};
Now I can do,
Expr* node = new IntNode();
node->GetType(); // returns ExprType::Const
node->GetConstType(); // return ConstNodeType::Int
Is this is good idiomatic way to create a hierarchy of classes? I basically want to check the type of an object of any subclass of Expr
.
I can do it in C# using the is
operator without a special type member.
Expr node = new IntNode();
assert(node is ConstNode);
assert(node is IntNode);
In C++, I can use RTTI, but is this the idiomatic way to create a class of hierarchies? Is there any alternative way to express the same hierarchy?