ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

Creating a ROS subscriber within a class constructor?

asked 2012-11-09 06:06:04 -0500

Ammar gravatar image

Hello All, I have a callback to some topic that is a method of a class. This works perfectly, except for the fact that I need to initialize this Subscriber within the main() function of my node. Ideally I would like to initialize it within the constructor of my class. Is there a way to do this? In simple terms I would like to add this line to the class constructor rather than main(): ros::Subscriber sub = n.subscribe("chatter", 1000, &Listener::callback, &listener);

Thanks Ammar

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
7

answered 2012-11-09 06:46:23 -0500

yigit gravatar image

updated 2012-11-09 14:48:45 -0500

Hi Ammar,

I think you have this problem because your subscriber object doesn't live outside its scope (constructor). You need to declare it as a private object in your class

private:
    ros:Subscriber sub;

then you can initialize it in the constructor:

sub = n.subscribe("chatter", 1000, &Listener::callback, &listener);

In the main function, when you create the object, you will have a running subscriber in your object.

edit flag offensive delete link more

Comments

Ahhh.... Great catch.. Thank you!!

Ammar gravatar image Ammar  ( 2012-11-09 07:16:14 -0500 )edit
3

answered 2015-06-29 03:04:55 -0500

Mehdi. gravatar image

Just in case somebody is wondering why it doesn't compile, In my case the accepted answer doesn't work and I have to do as follows:

sub = n.subscribe("chatter", 1000, &Listener::callback, this);
edit flag offensive delete link more

Question Tools

Stats

Asked: 2012-11-09 06:06:04 -0500

Seen: 3,864 times

Last updated: Jun 29 '15