title: Using the visitor pattern for an interpreter in C++
body: <p>I'm having trouble applying the visitor pattern for an interpreter in C++.  The following code produces (+) rather than ((1+2)+3) as desired:</p>
  
  <pre><code>class ExpVisitor{
  public:
      virtual void visit(class Add*)=0;
      virtual void visit(class Int*)=0;
  };
  
  class Exp{
  public:
      virtual void accept(ExpVisitor *v){};
  };
  
  class Add : public Exp{
  public:
      Exp e1,e2;
      Add(Exp in1,Exp in2){
          e1=in1;
          e2=in2;
      }
      void accept(ExpVisitor *v){
          v-&gt;visit(this);
      }
  };
  
  class Int : public Exp{
  public:
      int val;
      Int(int v){
          val=v;
      }
      void accept(ExpVisitor *v){
          v-&gt;visit(this);
      }
  };
  
  class PrintExp : public ExpVisitor{
  public:
      void visit(Add *e){
          cout  &lt;&lt; '(';
          (e-&gt;e1).accept(this);
          cout &lt;&lt; '+';
          (e-&gt;e2).accept(this);
          cout &lt;&lt; ')';
      }
      void visit(Int *e){
          cout &lt;&lt; e-&gt;val;
      }
  };
  
  
  int main(){
      Add e=Add(Add(Int(1),Int(2)),Int(3));
      PrintExp p;
      e.accept(&amp;p);
      cout &lt;&lt; endl;
  }
  </code></pre>
  
  <p>The problem, of course, is that Exp::accept is being called instead of than from Add or Int.  However, I can't make accept purely virtual since Add possess two members e1 and e2 of type Exp.  How can I fix this example?</p>