Note: This tutorial assumes that you have completed the previous tutorials: Writing a Simple Publisher and Subscriber, Writing a Simple Service. |
![]() |
Using Class Methods as Callbacks
Description: 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
Contents
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.
Subscriptions
Suppose you have a simple class, Listener:
Could not fetch external code from 'https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/listener_class/listener_class.cpp': HTTP Error 503: hostname doesn't match against certificate
Where the NodeHandle::subscribe() call using a function would have looked like this:
Could not fetch external code from 'https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/listener/listener.cpp': HTTP Error 503: hostname doesn't match against certificate
Using a class method looks like this:
Could not fetch external code from 'https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/listener_class/listener_class.cpp': HTTP Error 503: hostname doesn't match against certificate
Service Servers
Suppose you have a simple class, AddTwo:
Could not fetch external code from 'https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/add_two_ints_server_class/add_two_ints_server_class.cpp': HTTP Error 503: hostname doesn't match against certificate
Where the old NodeHandle::advertiseService() call would look like:
Could not fetch external code from 'https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/add_two_ints_server/add_two_ints_server.cpp': HTTP Error 503: hostname doesn't match against certificate
The class version looks like this:
Could not fetch external code from 'https://raw.github.com/ros/ros_tutorials/groovy-devel/roscpp_tutorials/add_two_ints_server_class/add_two_ints_server_class.cpp': HTTP Error 503: hostname doesn't match against certificate
For the full set of subscribe(), advertiseService(), etc. overloads, see the NodeHandle class documentation