|Note: This tutorial assumes that you have completed the previous tutorials: Writing a Simple Publisher and Subscriber, Writing a Simple Service.|
|Please ask about problems and questions regarding this tutorial on answers.ros.org. Don't forget to include in your question the link to this page, the versions of your OS & ROS, and also add appropriate tags.|
Using Class Methods as CallbacksDescription: Most of the tutorials use functions in their examples, rather than class methods. This is because using functions is simpler, not because class methods are unsupported. This tutorial will show you how to use class methods for subscription and service callbacks.
Tutorial Level: BEGINNER
if no code snippet is shown where it's supposed to be or anything strange in the code shown, please open the link. Code snippet macro might not be working well with github, which is being investigated.
Suppose you have a simple class, Listener:
Where the NodeHandle::subscribe() call using a function would have looked like this:
75 ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
Using a class method looks like this:
If the subscriber is inside the class Listener, you can replace the last argument with the keyword this, which means that the subscriber will refer to the class it is part of.
Suppose you have a simple class, AddTwo:
Where the old NodeHandle::advertiseService() call would look like:
45 ros::ServiceServer service = n.advertiseService("add_two_ints", add);
The class version looks like this:
For the full set of subscribe(), advertiseService(), etc. overloads, see the NodeHandle class documentation