Capturing Class Members in Lambdas

How can I capture member variables of a class when defining a lambda inside a member function?

When defining a lambda inside a member function of a class, capturing member variables works a bit differently than capturing local variables. To capture member variables, you need to explicitly use the this pointer.

Here's an example:

#include <iostream>

class Player {
  int health{100};

public:
  void TakeDamage(int amount) {
    auto PrintHealth{[this] {
      std::cout << "Remaining Health: "
        << this->health << '\n';
    }};

    health -= amount;
    PrintHealth();
  }
};

In this case, we capture this by value in the lambda. This gives us access to all the member variables and functions of the Player class inside the lambda.

Note that we need to use this-> to access the health member inside the lambda.

Alternatively, we could capture this by reference:

auto PrintHealth{[&] {
  // No "this->" needed
  std::cout << health << '\n';
}};

When capturing this by reference, we can directly access the members without using this->.

Lambdas

An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Returning Lambdas from Functions
Can I return a lambda from a function? If so, how do I specify the return type?
Using Lambdas in Template Functions
How can I pass a lambda as an argument to a function template?
Using Lambdas as Comparators
Can I use a lambda as a comparator for STL containers and algorithms?
Creating Stateful Lambdas
Is it possible to create a lambda that maintains state across multiple invocations?
Creating Recursive Lambdas
Can a lambda call itself recursively?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant