Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a helper function go in the header or in the implementation file?

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() {
    ...   
}
like image 525
rurouniwallace Avatar asked Oct 04 '12 22:10

rurouniwallace


People also ask

Should functions be in header files?

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.

Do helper functions go before or after?

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.

Should helper methods be above or below?

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.


1 Answers

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.

like image 88
Fred Foo Avatar answered Oct 03 '22 20:10

Fred Foo