CodeTheRobot

C++ Advanced · Lesson 02 of 23

Callbacks and lambdas

Passing behaviour into objects, binding member functions, and callback lifetimes.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain callbacks and lambdas in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

A callback is a function you give to an object, and it calls it later when something happens. ROS 2 subscriptions and timers work this way. A lambda is the most common form, and [this] lets the callback call member functions of the node that created it.

The danger is lifetime: a callback that captures this or a reference must not run after the node or variable is destroyed. Keep callbacks owned by the same object they call into, so both disappear together.

Guided lesson

Work through these steps

  1. 1.

    Read the callbacks and lambdas example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

class Subscriber {
// Owns a topic name and a callback, like a ROS 2 subscription.
public:
// Public interface.
  using Callback = std::function<void(const std::string&)>;
// Any callable taking a message string.
  Subscriber(std::string topic, Callback cb) : topic_{std::move(topic)}, cb_{std::move(cb)} {}
// Store the topic and the callback.
  void deliver(const std::string& msg) const { cb_(msg); }
// Call the stored callback with a message.
private:
// Hidden state.
  std::string topic_;
// The topic name.
  Callback cb_;
// The behaviour to run.
};
// End of the class.
class Logger {
// A node that wants to receive messages.
public:
// Public interface.
  Logger() : sub_{"/status", [this](const std::string& m) { last_ = m; }} {}
// The lambda captures this, so it updates the Logger's own member.
  std::string last_; Subscriber sub_;
// Members: last message and the subscription that owns the lambda.
};
// End of Logger; the lambda and the object have the same lifetime.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · Messages between nodes

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

/topicpublishersubscribersubscribermessages delivered: 0MESSAGES BETWEEN NODES

Demo for Callbacks and lambdas. Expected result: last: ready

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <functional>
#include <iostream>
#include <string>

class Subscriber {
 public:
  using Callback = std::function<void(const std::string&)>;
  explicit Subscriber(Callback cb) : cb_{std::move(cb)} {}
  void deliver(const std::string& msg) const { cb_(msg); }

 private:
  Callback cb_;
};

class Logger {
 public:
  // TODO: create sub_ with a lambda that captures this and stores the message in last_
  std::string last_;
  Subscriber sub_;
};

int main() {
  Logger logger;
  logger.sub_.deliver("ready");
  std::cout << "last: " << logger.last_ << '\n';
  return 0;
}

Expected output

last: ready
Stuck? Show the full solution (try it yourself first)
#include <functional>
#include <iostream>
#include <string>

class Subscriber {
 public:
  using Callback = std::function<void(const std::string&)>;
  explicit Subscriber(Callback cb) : cb_{std::move(cb)} {}
  void deliver(const std::string& msg) const { cb_(msg); }

 private:
  Callback cb_;
};

class Logger {
 public:
  Logger() : sub_{[this](const std::string& m) { last_ = m; }} {}
  std::string last_;
  Subscriber sub_;
};

int main() {
  Logger logger;
  logger.sub_.deliver("ready");
  std::cout << "last: " << logger.last_ << '\n';
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Build Subscriber and Logger as shown. Call deliver() three times and print last_. Then create a Subscriber whose lambda captures a local by reference and explain why calling it after the function returns would be a bug.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.