My class definition is spread across headers and source files:
// T.hpp
class T {
public:
void foo();
};
// T.cpp
void T::foo() {
}
If T::foo
needs to make use of some helper function that need be visible only to T
, which of the below solutions is best?
// T.hpp
class T {
public:
void foo();
private:
void helper();
};
// T.cpp
void T::foo() {
helper();
}
void T::helper() {
}
// T.hpp
class T {
public:
void foo();
};
// T.cpp
namespace {
void helper() {}
}
void T::foo() {
helper();
}
Is there any difference except that with the former I will end up with more functions in the header file?
You should make a function private when you don't need other objects or classes to access the function, when you'll be invoking it from within the class. Stick to the principle of least privilege, only allow access to variables/functions that are absolutely necessary.
A helper function is a function that performs part of the computation of another function. Helper functions are used to make your programs easier to read by giving descriptive names to computations. They also let you reuse computations, just as with functions in general.
Prefer free, non-friend functions over member functions, because these have less access to class members than member functions, and therefore have less of a chance to introduce bugs.
If the function is completely outside the interface scope then also put it in an unnamed namespace in the implementation file. This will reduce the chance of bugs even further, because other translation units will not be able to call the function.
Another advantage you get with a non-friend in an unnamed namespace is that there's less of a chance you change the header (since there's one less entity in there). Changing a header file often slows down build times considerably, because of the compile-time dependencies. Private or not, you'll probably have a number of translation units depending in terms of compilation on everything in the header.
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