title: Can I create anonymous classes in C++ and capture the outside variables like in Java?
body: <p>In Java, when I need a callback function, I have to implement an anonymous class. Inside the anonymous class, I can access the outside variables if they're <code>final</code>.</p>
  
  <p>Now I'm doing the same thing in C++. I understand that C++ lambda works better but sometimes I need to pass in many functions where with anonymous classes, I only need to pass in one instance.</p>
  
  <p>I tried the following example. It works with GCC 4.3.4.</p>
  
  <pre><code>class IA {
  public:
    virtual int f(int x) = 0;  
  };
  
  int main() {
      class : public IA {
          int f(int x) { return x + 1; }
      } a;
      doFancyWork(&amp;a);
      return 0;
  }
  </code></pre>
  
  <p>Is it possible to capture the outside variables like this?</p>
  
  <pre><code>int main() {
      int y = 100; // mark y as final if possible
      class : public IA {
          int f(int x) { return x + y; }
      } a;
      return 0;
  }
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>The second example won't compile. The errors are here,</p>
  
  <pre><code>prog.cpp: In member function ‘virtual int main()::&lt;anonymous class&gt;::f(int)’:
  prog.cpp:9: error: use of ‘auto’ variable from containing function
  prog.cpp:7: error:   ‘int y’ declared here
  prog.cpp: In function ‘int main()’:
  prog.cpp:7: warning: unused variable ‘y’
  </code></pre>
  
  <p>UPDATE:</p>
  
  <p>I just realized a few more problems in doing this:</p>
  
  <ul>
  <li>I cannot write a constructor because the class doesn't have a name</li>
  <li>initializer list doesn't allow inheritance.</li>
  <li>any change to make it compile makes the code unreadable.</li>
  </ul>
  
  <p>I think I have to move away from anonymous classes.</p>