Function Pointers

Capturing this in Lambdas

How can I use a lambda to create a function pointer that calls a member function of my class?

Abstract art representing computer programming

In C++, lambdas can capture the this pointer, allowing them to call member functions of the enclosing class. This can be useful when you need to create a function pointer that wraps a member function. Here's an example:

#include <iostream>

class Player {
 public:
  bool isAlive() const { return mAlive; }
  void setAlive(bool Alive) { mAlive = Alive; }

  template <typename Func>
  void useHealthPotion(Func&& onHealthRestored) {
    mAlive = true;
    onHealthRestored();
  }

 private:
  bool mAlive{true};
};

int main() {
  Player MyPlayer;
  MyPlayer.setAlive(false);

  MyPlayer.useHealthPotion([&MyPlayer]() {
    if (MyPlayer.isAlive()) {
      std::cout << "Health restored!\n";  
    }
  });
}
Health restored!

In this example, the Player class has a useHealthPotion member function that takes a function pointer (or any callable object) as an argument. We use a lambda to create this function pointer inline.

The lambda captures MyPlayer by reference using [&MyPlayer]. This allows the lambda to access MyPlayer and call its member functions, such as isAlive().

When useHealthPotion is called, it sets the player's mAlive state to true and then invokes the provided function pointer (onHealthRestored). The lambda, which captures MyPlayer, is able to call MyPlayer.isAlive() to check the player's state and print a message.

By capturing this (explicitly or implicitly), lambdas can create function pointers that have access to the enclosing class's member functions and state. This can be a convenient way to create callback functions or hook into class functionality without having to define separate free functions.

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