Ask Your Question

C++ How to set a callback to point to a non-static member function of an object instance?

asked 2014-05-04 02:50:41 -0500

Nap gravatar image

[Ubuntu 13.10, Hydro Desktop-Full from source, C++]

I am having difficulty setting up callback functions for my ROS Topic subscribers, and would appreciate help.

Since all my Topics use the std_msgs::String type, I've defined the class shown below with a generic callback function and an instance variable which identifies the specific Topic.

class myCallback {

        const char * eventtype;


        myCallback(const char * eventType) : eventtype(eventType) {}

        void generic_callback(const std_msgs::String::ConstPtr& msg) {
            std::cerr << this->eventtype << " heard: " << msg->data.c_str() << std::endl;


For the ROS functionality in my project, I've created a separate class gwrbclass.cpp & gwrbclass.h, which include the myCallback class. In the header file, I define myCallback *callbackList[NUM_EVENT_TYPES] as a private variable. In the implementation, I instantiate the required myCallback objects for each entry in the callbackList and try to bind it to the node's subscriber object as shown below:

for (int j=0; j<NUM_EVENT_TYPES; j++) {
    callbackList[j] = new myCallback(eventName);
    subList[j] = (sNode[j])->subscribe(eventName, 1000, callbackList[j]->generic_callback);  << ERROR OCCURRING HERE

I'm getting an error stating : reference to non-static member function must be called , and as far as I can see, the method I'm calling is not static and therefore should work.
If I use subList[j] = (sNode[j])->subscribe(...., &callbackList[j]->generic_callback); the error becomes : cannot create a non-constant pointer to member function.

I'm confused as to why I'm getting this error (which I believe has something to do with std::bind, function typedef, wrapper functions, etc), and would appreciate some help as I can't figure out the syntax.

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2014-05-04 08:41:27 -0500

fergs gravatar image

You need to use the class member version of subscribe -- the doxygen for it is here.

Basically, it would be:

(sNode[j])->subscribe(eventName, 1000, &myCallback::generic_callback, callbackList[j]);
edit flag offensive delete link more


Thank you Fergs, exactly what was needed. :)

Nap gravatar image Nap  ( 2014-05-04 17:57:05 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2014-05-04 02:50:41 -0500

Seen: 15,464 times

Last updated: May 04 '14