In C++ definition file (.cpp), sometimes I can define small functions to be invoked, for example:
// Class declaration
// Myclass.h
Class Myclass
{
...
void Classfunction();
...
}
// Class defination
// Myclass.cpp
#include "Myclass.h"
...
void helper_fun()
{
...
}
...
void Myclass::Classfunction()
{
...
helper_fun();
...
}
In the above example, we can see void helper_fun() is declared and defined in the .cpp file. The purpose of this function is to be invoked by the functions that have been defined in the class. Of course, the helper_fun can be declared in the head file first and then defined in the implementation file. My question is whether this is a good practice for C++ code writing. Moreover, does this practice have some bad effects? Thanks!
Having local helper functions in the source files are very common. Normally they are either declared as
static(e.g.static void helper_fun() { }) or in an anonymous namespace (e.g.namespace { void helper_fun() { } }).Making the functions static or having them in an anonymous namespace is so that they wont be callable from the outside, and so that you can have more local functions with the same name.
If, however, you want to call the function from other source files, then define the function normally, and add a declaration in the header file.