title: Calling private function in lambda from outside the class
body: <p>In my current project I am trying to pass a private member function as parameter to another function. In my code, the other function is a member function of a different class, but for keeping it simple, here it is a free function.</p>
  
  <pre><code>void outside_function(std::function&lt;void(int)&gt; func) {
    // do something with func
  }
  
  
  class MyClass {
  public:
    void run();
  
  private:
    bool my_func(double); // defined in source file
  };
  </code></pre>
  
  <p>Now, from inside <code>run</code> I want to put <code>my_func</code> into <code>outside_function</code> as argument. Since the signature of <code>run</code> does not fit the requirements for the parameter, I cannot simply pass it. Using the <a href="https://en.wikipedia.org/wiki/Adapter_pattern" rel="nofollow noreferrer">adapter pattern</a> was my first try, which was when I was reminded that member functions implicitly take the <code>this</code> pointer as first argument. <a href="https://stackoverflow.com/a/7582576/6608142">This</a> answer suggests using a lambda expression, which is what I did.</p>
  
  <pre><code>void MyClass::run() {
    outside_function([this](int a) -&gt; void {
      double d = static_cast&lt;double&gt;(a);
      this-&gt;my_func(d);
    });
  }
  </code></pre>
  
  <p>Why does this work? From my point of understanding, <code>outside_function</code> does not have access to <code>my_func</code>. Why don't I have to make <code>my_func</code> public first? Is it something the compiler does or some C++ rule I don't know?</p>
  
  <p>Additionally, are there any catches to this approach that might break my code?</p>