Allen Yuan
Allen Yuan

Reputation: 97

In C++ (class), do I always need to declare function in the header file?

For example, I have a markerdisplay.cpp file. The markerdisplay member function will look like the below code.

void MarkerDisplay::setMarkerStatus(MarkerID id, StatusLevel level, const std::string& text)
        {
               .....
        }

Can I have a non-member function in the markerdisplay.cpp?

For example,

bool validateFloats(const visualization_msgs::Marker& msg)
        {
              ...
        }

The function validateFloats is not a member function, and I also don't declare it in the header file. I only use this function inside of the validateFloats.cpp file.

Someone told me this may cause some problems. Is that true?

Upvotes: 8

Views: 3132

Answers (2)

Baum mit Augen
Baum mit Augen

Reputation: 50111

If you don't need the function outside of the .cpp, it is sufficient to declare and define it in that file. Of course you will still have to declare it before first use, but that is the only "problem" I can think of.

It is rather a good idea not to declare the function in the header if not needed because you use up fewer "project-public" names and make it easier to find all uses of the function, thus making the code more maintainable.

If you don't declare the function in your header, you should make it static:

static bool validateFloats(const visualization_msgs::Marker& msg);

or put it in an anonymous namespace:

namespace {
    bool validateFloats(const visualization_msgs::Marker& msg);
}

(preferred) to avoid accidental cross-translation-unit name clashes.

Upvotes: 16

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

my question is: can I have non member function in the markerdisplay.cpp for example ...

Yes, you can do that.

The best choice would be to provide that function in the implementing translation unit if it's not intended to be used from the public API.

You can even completely hide that (including the linker) in an anonymous namespace

namespace {
    bool validateFloats(const visualization_msgs::Marker& msg) {
       // ...
    }
}

Alternatively just defining a static function in the translation unit should have the same effect:

static bool validateFloats(const visualization_msgs::Marker& msg) {
   // ...
}

Upvotes: 7

Related Questions