# Initialize constant message

How do I initialize a constant message (with 2+ fields) in a class constructor? This is more of a raw C++ question but intertwined with some ROS complications. Some background:

• for the class I'm writing it makes sense to have a member that is a message, as this will be used to command a grasp via an actionlib client so it's preemptable;
• it would make sense for the message itself to be constant, since it's not going to change in this particular implementation (I only want to be able to grasp this kind of object with this width and this speed, etc), and possibly even static;
• the message class doesn't have a constructor, as most (if not all) messages do, and I'd rather not write a constructor myself as it seems it's not a good way to deal with the problem because of how messages were designed;
• the initializer list doesn't accept (or seem to accept) parameters;
• I didn't manage to find non-ROS C++ examples that weren't using a constructor to solve the issue;
• if I don't set it as constant I can initialize it in the body of the constructor, of course, but I think what I'm saying about the need for it to be constant makes sense.

ROS kinetic, Ubuntu 16.04, kernel 4.8.15-rt10, libfranka 0.5.0, franka_ros 0.6.0

edit retag close merge delete

Sort by » oldest newest most voted

Though it may not be the "cleanest" solution, you can initialize the const message in the initialization list of the class using the lambda initialization trick (See https://stackoverflow.com/q/11037650 and https://herbsutter.com/2013/04/05/com... ). This trick seems to be underutilized in the C++ community even though it's been available since C++11.

more

Based on @kartikmohta's answer, an example of initializing a constant std_msgs::String is as follows

const std_msgs::String MY_STRING = []{
std_msgs::String ret;
ret.data = "hello";
return ret;}();

more