C++, do private functions really need to be in the header file?

PImpl idiom is needed only

  1. if you need to move private member 'variables' out of public header ( For maintaining binary compatibility of new releases - If you don't know what that means, it is likely not a concern )
  2. If that design makes it easier to understand

If you only want to move private member 'functions' out of public header, using an inner class is enough. This does not have redirection penalty like PImpl idiom.

public .h file

#ifndef SOME_CLASS_H
#define SOME_CLASS_H

class SomeClass
{
private:
    struct Private;
    int x;
public:
    void combineWithX(int y);
};

#endif

in .cpp file

#include "SomeClass.h"

/** Declare all private member functions of SomeClass here
    This class can access not only private members of SomeClass
    but also friends of SomeClass. */
struct SomeClass::Private
{
  static void someHelper(SomeClass& self)
  {
    self.x = self.x + 1;
  }
};

void SomeClass::combineWithX(int y)
{
    Private::someHelper(*this);
    x += y;
}

SomeClass::Private can have any number of helper functions that has full access to all private/friends of SomeClass, without having to declare any of them in header file.


I agree that it is a problem that implementation details need to be exposed in a header file; it interferes with separation of interface and implementation.

Moving private helper functions to be free functions in the .cpp file (I presume that is what you meant by "static") won't work if those functions need to access private member variables.

You may be interested to look at the pImpl idiom (more)