3

I know this question had been asked many times but I'm still stuck. I thought I got what this error was about what obviously I don't.

So, the error I am getting is

a nonstatic member reference must be relative to a specific object

My code is:

class theTranslator {
public:
    ros::NodeHandle nh;

    ros::Publisher pub = nh.advertise<sensor_msgs::Image>("camera/depth/image_raw", 100);

    static void getMessage(const sensor_msgs::Image::ConstPtr& recMmsg) {
        ROS_INFO( "I heard message" );
        pub.publish(recMmsg); //*** ERROR IS HERE ***
    }
};

since pub is part of the same class as getMessage(), shouldn't it work? How can I make a static member function use a variable member of the same class?

P.S. this is done in ROS (Robotics Operating System) but I believe this is a C++ mistake (not related to ROS).

Student
  • 805
  • 1
  • 8
  • 11
Metalzero2
  • 531
  • 2
  • 6
  • 17
  • How would the compiler know which object's pub member to use? You have to send in e.g. a pointer or reference to an actual theTranslator object as a param to getMessage, and access the pub member of that instance. But normally, static member fcns access only static data. – Erik Alapää Jul 27 '18 at 09:54

2 Answers2

5

In C++ you can not access a non static class member from a static method. Make it a normal method and try like below:-

 void getMessage(const sensor_msgs::Image::ConstPtr& recMmsg){
        ROS_INFO( "I heard message" );
        pub.publish(recMmsg); //*** ERROR IS HERE ***
    }

Else declare pub as static member

static ros::Publisher pub; 

Also refer to the below answer

C++ static member functions and variables

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
  • well that sucks. I thought if the are in the same class, it is correct. With my current design, I can't do what you suggest. Back to the whiteboard I guess. Thanks. – Metalzero2 Jul 27 '18 at 09:59
1

You need to make getMessage non-static or you need to make pub static.

Probably what you really need to do is rethink your design. Why are you trying to make getMessage static? As a very general rule of thumb static is a mistake, especially for a newbie.

john
  • 85,011
  • 4
  • 57
  • 81
  • It is related to how ROS handles message transmission between nodes. You are right, I need to redesign my code. Thanks. – Metalzero2 Jul 27 '18 at 10:00
  • 1
    @DimitrisPantelis Usually the motivation for making a member function static is because you need to use it as a callback. It's a well known problem, how to get from a callback function to an object. Some googling will probably help. – john Jul 27 '18 at 10:07
  • actually that is what I want, use it as a callback. will google it. – Metalzero2 Jul 27 '18 at 10:09