0
$\begingroup$

Rosanswers logo

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


Originally posted by Ammar on ROS Answers with karma: 289 on 2012-11-09

Post score: 0

$\endgroup$

2 Answers 2

0
$\begingroup$

Rosanswers logo

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.


Originally posted by yigit with karma: 796 on 2012-11-09

This answer was ACCEPTED on the original site

Post score: 7


Original comments

Comment by Ammar on 2012-11-09:
Ahhh.... Great catch.. Thank you!!

$\endgroup$
0
$\begingroup$

Rosanswers logo

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);

Originally posted by Mehdi. with karma: 3339 on 2015-06-29

This answer was NOT ACCEPTED on the original site

Post score: 3

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.