title: Can I create an anonymous on-the-fly class (implementation of an interface) in C++
body: <p>In C++, can I create an implementation of an interface on the fly (which ideally binds local-scope variables.) Not sure how to explain it better, so I will put down what I would like the code to look like (roughly):</p>
  
  <pre><code>// Given the following:
  
  class Visitor
  {
      virtual void visit(const Data&amp; data) = 0;
  }
  
  class DataStore
  {
      void visitData(Visitor&amp; visitor) { /** Invokes visitor with each item of data. */ }
  }
  
  // Imagine one would write something like:
  
  void inSomeFunction(DataStore&amp; store)
  {
      std::string myName = "bob";
  
      class MyVisitor: public Visitor
      {
      public:
          MyVisitor(const std::string&amp; p): person(p);
          virtual void visit(const Data&amp; data) override
          {
              std::cout &lt;&lt; person &lt;&lt; " is visiting " &lt;&lt; data &lt;&lt; std::endl;
          }
      private:
          std::string person;
      }
  
      MyVisitor myVisitor(myName);
      store.visitData(myVisitor);
  }
  
  // Instead of the above, I want to write instead something like:
  
  void inSomeFunction(DataStore&amp; store)
  {
      std::string myName = "bob";
  
      store.visitData(
          class: public MyVisitor
          {
              virtual void visit(const Data&amp; data) override
              {
                  std::cout &lt;&lt; myName &lt;&lt; " is visiting " &lt;&lt; data &lt;&lt; std::endl;
              }
          }
      );
  }
  </code></pre>
  
  <p>I realise that I'm asking 2 questions here - can you create an anonymouse class like this, and can you bind variables from the local scope (like I've referred to myName). But I need both for it to be useful.</p>
  
  <p>If the above can't be done, what's the closest one can get to using say C++11 lambdas or similar, in terms of conciseness / lack of boilerplate.</p>