title: How do I store a pointer to a derived class in an instance variable declared as a pointer to a base class?
body: <p>I am trying to write a toy language interpreter in C++. I am having trouble with the AST classes. The parent <code>ASTNode</code> class declares its left-branch and right-branch pointers as <code>ASTNode*</code>like this:</p>
  
  <pre><code>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;
  
  }
  </code></pre>
  
  <p>The <code>ASTNode</code> class has a subclass called ValNode. It has a method that returns its value (stored in a member variable):</p>
  
  <pre><code>class ValNode : public ASTNode
  {
      public:
          explicit ValNode(const Variant&amp; newvalue);
  
          const Variant&amp; getValue() const;
  
      private:
          Variant value;
  }
  </code></pre>
  
  <p>When I execute the following code, the program crashes due to a failed <code>dynamic_cast</code>. What's wrong, and how can I fix it?</p>
  
  <pre><code>ASTNode* node = new ASTNode(NodeType::OP, new ValNode(1), new ValNode(2));
  cout &lt;&lt; dynamic_cast&lt;const ValNode*&gt;(node-&gt;getLeft())-&gt;getValue() &lt;&lt; endl;
  </code></pre>