I am trying to write a toy language interpreter in C++. I am having trouble with the AST classes. The parent ASTNode
class declares its left-branch and right-branch pointers as ASTNode*
like this:
class ASTNode {
public:
ASTNode(NodeType newType, const ASTNode* left, const ASTNode* right);
const ASTNode* getLeft() const;
const ASTNode* getRight() const;
protected:
//node type omitted
ASTNode* left;
ASTNode* right;
}
The ASTNode
class has a subclass called ValNode. It has a method that returns its value (stored in a member variable):
class ValNode : public ASTNode
{
public:
explicit ValNode(const Variant& newvalue);
const Variant& getValue() const;
private:
Variant value;
}
When I execute the following code, the program crashes due to a failed dynamic_cast
. What's wrong, and how can I fix it?
ASTNode* node = new ASTNode(NodeType::OP, new ValNode(1), new ValNode(2));
cout << dynamic_cast<const ValNode*>(node->getLeft())->getValue() << endl;