How to structure a node to publish a topic using classes? [closed]
I am writing a node but I have some doubts of how to structure it if I am using classes. Right now I have written two methods. The first one is:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
class node_class
{
public:
node_class();
private:
ros::NodeHandle nh_;
ros::Publisher pub_;
std_msgs::String msg;
ros::Rate loop_rate;
};
node_class::node_class():
pub_(nh_.advertise<std_msgs::String>("chatter", 10)),
loop_rate(1)
{
msg.data = "hello world";
while(ros::ok())
{
pub_.publish(msg);
loop_rate.sleep();
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "node_class");
node_class this_node;
while(ros::ok())
ros::spinOnce();
return 0;
}
In this one the loop is done inside the constructor, but I have my doubts about it. Also the ros::ok()
is checked twice. And the second method is:
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
class node_class
{
public:
node_class();
void loop_function();
private:
ros::NodeHandle nh_;
ros::Publisher pub_;
std_msgs::String msg;
ros::Rate loop_rate;
};
node_class::node_class():
pub_(nh_.advertise<std_msgs::String>("chatter", 10)),
loop_rate(1)
{
msg.data = "hello world";
}
void node_class::loop_function()
{
pub_.publish(msg);
loop_rate.sleep();
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "node_class");
node_class this_node;
while(ros::ok())
{
this_node.loop_function();
ros::spinOnce();
}
return 0;
}
Here I am using a loop_function
from the class to be executed in the main while loop
. Both methods work but, are there other methods or best practices to do this?