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