Lambdas

Capturing Class Members in Lambdas

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

Abstract art representing computer programming

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved