How to initialize another node inside the member of a class?

asked 2020-04-07 03:54:09 -0500

Suri gravatar image

Hey all, I am new to ros. I have a class called plugin node (default constructor). But plugin node class has a method called Initialize(), where I do the node initialization for "sim" node along with remapping. but I need to initialize another node called cleaning.

  1. Is it okay if I do another node initialization inside the class method Initialize() or if I define one more method InitiliazeCleaning() in a plugin node class, to initialize cleaning node and call the new method inside Initialize() method?.

2.Or else, I just need to know any way to add topic cleaning inside the sim node. cleaning topic has a separate class.

Cleaning class

namespace Sim {

Cleaning::Cleaning(ros::NodeHandle *nh) :m_nh{&nh}
    service = m_nh.advertiseService("cleaning", &Cleaning::CallBackCleaning, this);

 bool  Cleaning::CallBackCleaning(kira_msgs::Cleaning::Request &req, kira_msgs::Cleaning::Response &res){
     ROS_INFO("cleaning service is advertised");
     return true;

PluginNode method implementation

bool PluginNode::Initialize()
    auto remappings = LoadRosRemappings();
    ros::init(remappings, "sim", ros::init_options::NoSigintHandler);
    signal(SIGINT, ExitSimuSigHandler);
if (!ros::master::check())
    ROS_ERROR("ROS master must be running");
    return false;

m_nh = std::make_unique<ros::NodeHandle>(ros::this_node::getName());

And I read lot of documentation, but still it is not clear to me. should we have NodeHandler for each node?.

If you have any documentation related to my questions, kindly feel free to share. If possible I will try to get answer for my question. Thanks in advance.

edit retag flag offensive close merge delete



Hi @Suri,

I did not understand very well your question but nodes are individual ROS entities and there is no good reason to initialize a node inside a node, actually the class itself should not initialize the node since that particular task is usually done by the main process. In order to anwer you question I will say that you can generate two separate classes (Cleaning and PluginNode in your case) and use them in the main function of the node. That is:

class A
A{ros::nodehandle *nh}

class B
B{ros::nodehandle *nh}

int main
ros::nodehandle nh;
A a(&nh)
B b(&nh)
Weasfas gravatar image Weasfas  ( 2020-04-07 14:43:21 -0500 )edit