When writing a helper method for a class in C++, should it be declared as a private method in the class’s definition in the header (.h) file? For example:
/*Foo.h*/
class Foo {
public:
int bar();
private:
int helper();
};
...
/*Foo.cpp*/
...
int foo::bar() {
int something = this->helper();
}
int foo::helper() {
...
}
Or alternatively, is it better not to declare it as a private member of the class, and instead just make it a free-standing function in the implementation?
/*Foo.h*/
class Foo {
public:
int bar();
};
...
/*Foo.cpp*/
...
int Foo::bar() {
int something = helper();
...
}
int helper() {
...
}
A freestanding function in the implementation file improves encapsulation: it needs no declaration in the header, so no recompilation of client code when its signature changes for whatever reason. For me, that’s a good enough reason to prefer this option whenever it’s feasible. (Be sure to put it in the anonymous namespace to prevent identifier clashes at link time.)
However, a
privatemethod has access to a class instance and its private parts via thethispointer. If it needs such access, then it must either be a method or afriend. In both cases, it’ll be visible in the class definition (header file), and methods are simply more convenient than friends.