2

I am trying to understand this line of code

 ros::Rate loop_rate(10);

It seems to be creating some kind of object, however this looks like a function call and I don't see where the object is named. What is this line of code doing? I understand what loop_rate is in ros, but I am new to c++ and don't understand the syntax.

#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>

int main(int argc, char **argv)
{
  ros::init(argc, argv, "talker");

  ros::NodeHandle n;

  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);

  ros::Rate loop_rate(10);



  int count = 0;
  while (ros::ok())
  {
    std_msgs::String msg;

    std::stringstream ss;
    ss << "hello world " << count;
    msg.data = ss.str();

    ROS_INFO("%s", msg.data.c_str());

    chatter_pub.publish(msg);

    ros::spinOnce();

    loop_rate.sleep();
    ++count;
  }


  return 0;
}
Alexis Winters
  • 487
  • 1
  • 5
  • 18

2 Answers2

5

It's nothing sinister.

In fact, it's a pretty straightforward variable declaration.

The type is ros::Rate, the name is loop_rate, and the sole constructor argument is 10.

It does look a bit like a function call, but it isn't one. (It also looks a bit like a function declaration, which can cause problems if you're not careful!)

It's like:

std::string str("Hi!");

or:

Rectangle rect(10, 5);

or even:

int x(42);

In the case of built-ins, many of us tend to use old-style copy-initialisation instead:

int x = 42;

… though this is not so feasible for most class types.

Do you perhaps need to review declaration syntax in your C++ book?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

Rate is a type included in ros/ros.h which is used to give a specific time period for a task.

Thus it has been written as:

ROS:: Rate variable_name(time_delay_HZ); 

You can give any name to your variable they have given loop_rate and you can give any time delay in HZ (10HZ=100ms).

Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100