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->
.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to lambda expressions - a concise way of defining simple, ad-hoc functions