Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
Accessing private member function via Lambda

In a project, I have a C-API which uses C-style function pointers as callbacks. In one of those callbacks, I need to access a private function of an object Foo. Note that the API-call is done within a function of my class. Because of not shown code, I have a handle to my object as a void* accessible to me.

Things aside that the construct is prone to errors, by passing a lambda as callback I am able to access the private function of my object. This is somewhat unexpected but welcome to me. I haven't found anything regarding this behavior, so I would kindly ask if somebody could shed some light why this is actual working. I am not aware that the lambda is catching something, but it appears that is has something to do with the actual scoping. I am using C++17 and gcc 10.2.

Here's a sample block of code:

void TestFunc(void (*)(void*)) {
}

class Foo {
public:
    Foo() {
     TestFunc([](void* handle){
         auto foo = reinterpret_cast<Foo*>(handle);
         foo->BarFunc();
     });
    };
private:
    void BarFunc() {};
};
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Your code is working because Standard allows it. So first we have this (C++20 [expr.prim.lambda.closure]p2):

The closure type is declared in the smallest block scope, class scope, or namespace scope that contains the corresponding lambda-expression. <...>

And in your example we have a block scope so in the end we have an unnamed local class declaration and according to [class.local]p1:

A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!