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() {
...
}
No. If you import the same header from two files, you get redefinition of function. However, it's usual if the function is inline. Every file needs it's definition to generate code, so people usually put the definition in header.
Generally, the most important things should come first, with less important things later. In a class this means that the members and the constructor should come first, followed by public methods that make up the API of the class. After that, (private) helpers are listed.
According to Clean Code you should order your methods from top to bottom, in the order they are called. So it reada like a poem.
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 private
method has access to a class instance and its private parts via the this
pointer. If it needs such access, then it must either be a method or a friend
. In both cases, it'll be visible in the class definition (header file), and methods are simply more convenient than friends.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With