Search code examples
c++includedefault-valuerosforward-declaration

C++ (and ROS) - Include vs. forward declare of reference with set default and typedef


I have two very related questions regarding forward declarations, their advantages and difference with #includes. After reading on them it's still unclear to me if:

  • using a ConstPtr from a ROS message (like this) counts as a pointer and can be (somehow) forward declared, or requires an #include;

  • void foo(const Eigen::Vector3d& scale={0.001, 0.001, 0.001}); in a .h file would be fine with something like (but this doesn't actually compile)

    namespace Eigen
    {
    
    class Vector3d;
    }
    

at the top of the .h after all the other #includes or if I should use the proper header.

To be clear, the second issue is with the fact scale has a default value, which is actually the one I will always be using in the .cpp. This is the only instance where I'm using a Vector3d.

I'm also fairly certain if the forward declaration is enough I therefore would not need to include the proper header in the .cpp as well, since I'm only ever using the default value inside the method.


Solution

  • A forward declaration of X is sufficient to use an X* or X& as a function parameter or class member, because the full definition of a class is not needed to be able to use its address.

    But in order to create an object of that class, even one with a default value, you're going to need its definition.