Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The way you pass a Node from one C++ class to another is with shared_from_this() and std::shared_ptr.

Example:

Class A inherits from rclcpp::Node. Get the node pointer like this:

auto node_ptr = shared_from_this();

Pass to another class (Class B) like this:

pointer_to_class_b_object = std::make_shared<ClassB>(node_ptr);

The constructor of Class B should take a rclcpp::Node::SharedPtr node:

ClassB(rclcpp::Node::SharedPtr node) : node_(node)
{
}

And it should have a private member variable:

  // Pointer to the ROS node
  std::shared_ptr<rclcpp::Node> node_;

ROS2 documentation is still lacking, I think.

The way you pass a Node from one C++ class to another is with shared_from_this() and std::shared_ptr.std::shared_ptr.

Example:

Class A inherits from rclcpp::Node. Get the node pointer like this:

auto node_ptr = shared_from_this();

Pass to another class (Class B) like this:

pointer_to_class_b_object = std::make_shared<ClassB>(node_ptr);

The constructor of Class B should take a rclcpp::Node::SharedPtr node:

ClassB(rclcpp::Node::SharedPtr node) : node_(node)
{
}

And it should have a private member variable:

  // Pointer to the ROS node
  std::shared_ptr<rclcpp::Node> node_;

ROS2 documentation is still lacking, I think.lacking and it helps to be a C++ guru :/

The way you pass a Node from one C++ class to another is with shared_from_this() and std::shared_ptr.

Example:

Class A inherits from rclcpp::Node. Get the node pointer like this:

auto node_ptr = shared_from_this();

Pass to another class (Class B) like this:

pointer_to_class_b_object shared_pointer_to_class_b_object = std::make_shared<ClassB>(node_ptr);

The constructor of Class B should take a rclcpp::Node::SharedPtr node:

ClassB(rclcpp::Node::SharedPtr node) : node_(node)
{
}

And it should have a private member variable:

  // Pointer to the ROS node
  std::shared_ptr<rclcpp::Node> node_;

ROS2 documentation is still lacking and it helps to be a C++ guru :/