Suppose you have the following non-static member function:
// .h
struct C {
void f();
}
Now suppose you want to implement C::f
by using some sub-functions specific to C::f
, to make it shorter and more readable; for example:
// .cpp
void C::f() {
h1();
h2();
//...
hn();
}
suppose that many of those h()'s functions do not need to access any data members. This means that you may well define the functions either as static free functions (in one .cpp) or as member functions (static or not).
Would you make them static free functions or function members of C?
One advantage in the first case is that you will not have to declare them in C
:
// .cpp
static void h1() {//...}
static void h2() {//...}
static void hn() {//...}
Also, if I am not wrong, there is no risk of global namespace pollution, since they are static, that is they can only be seen from other functions inside the same unit .cpp (in which C::f is also defined).
while in the second case you will have to declare them in C
, although, as I said, they are only supposed to be used by C::f
.
// .h
struct C {
void f();
private:
static void h1(); // can be either static or non-static
static void h2();
static void hn();
}
// .cpp
void C::h1() {//...}
void C::h2() {//...}
void C::hn() {//...}
I think the second version results in bloated code for no good reason, above all if you end up having to split other long member functions like C::f
to make the code more readable.