There are two reasons for doing this.
First, realize that the access specifier is for the compiler, and is not relevant at runtime. Accessing a private member outside of scope is a compile error.
Conciseness
Consider a function that is short, one or two lines. It exists to reduce the replication of code elsewhere, which also has the advantage of being able to change how an algorithm or whatever else works in one place instead of many (e.g. changing a sorting algorithm).
Would you rather have a quick one or two line in the header, or have the function prototype there plus an implementation somewhere? It is easier to find in the header, and for short functions, it is far more verbose to have a separate implementation.
There is another major advantage, which is...
Inline Functions
A private function may be able to be inlined, and this necessarily requires it to be in the header. Consider this:
class A {
private:
inline void myPrivateFunction() {
...
}
public:
inline void somePublicFunction() {
myPrivateFunction();
...
}
};
The private function may be able to be inlined along with the public function. That is done at the compiler's discretion, as the inline
keyword is technically a suggestion, not a requirement.