CodeTheRobot

C++ Advanced · Lesson 01 of 23

Class-based node-like structures

A class that owns its state, publishers and timers, the shape every ROS 2 node has.

Estimated time · 60–90 min

Learning goals

What you will understand

  • Explain class-based node-like structures 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 ROS 2 node is a class that owns everything it needs (name, parameters, publishers, subscriptions, timers) and sets it up in its constructor. Practise that shape now with a plain C++ class: a name, a configuration, some state, and small methods that react to events.

Keep the constructor for wiring and the methods for behaviour. Store dependencies as members so their lifetime equals the node's lifetime (RAII), and avoid globals so that several nodes can run in one process.

Guided lesson

Work through these steps

  1. 1.

    Read the class-based node-like structures 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 TemperatureNode {
// A node-like class that owns its own name and state.
public:
// Public interface.
  explicit TemperatureNode(std::string name) : name_{std::move(name)} {}
// Store the node name; the constructor only wires things up.
  void on_sample(double celsius) {
// Behaviour: react to a new reading.
    last_ = celsius;
// Remember the latest value.
    if (celsius > limit_) std::cout << name_ << ": too hot\n";
// Report a problem, tagged with the node name.
  }
// End of on_sample.
  const std::string& name() const { return name_; }
// Read-only access to the name.
private:
// Hidden state.
  std::string name_;
// The node's identity.
  double limit_{80.0};
// Configured alarm limit.
  double last_{0.0};
// Most recent reading.
};
// End of the class.

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 Class-based node-like structures. Expected result: arm: too hot

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 <iostream>
#include <string>

class TemperatureNode {
 public:
  explicit TemperatureNode(std::string name) : name_{std::move(name)} {}
  // TODO: write on_sample(): store the value in last_ and print "<name>: too hot" when it is above limit_

 private:
  std::string name_;
  double limit_{80.0};
  double last_{0.0};
};

int main() {
  TemperatureNode node{"arm"};
  node.on_sample(70.0);
  node.on_sample(85.0);
  return 0;
}

Expected output

arm: too hot
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <string>

class TemperatureNode {
 public:
  explicit TemperatureNode(std::string name) : name_{std::move(name)} {}
  void on_sample(double celsius) {
    last_ = celsius;
    if (celsius > limit_) std::cout << name_ << ": too hot\n";
  }

 private:
  std::string name_;
  double limit_{80.0};
  double last_{0.0};
};

int main() {
  TemperatureNode node{"arm"};
  node.on_sample(70.0);
  node.on_sample(85.0);
  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

Write two node-like classes, TemperatureNode and FanNode, each with a name and a callback method. Create both in one main() and drive them with a loop of fake readings.

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.