C++ – Why Put Private Member Functions in Headers?

chistory

The answer to why we put private member variables in C++ headers is that the size of the class must be known at points where instances are declared so that the compiler can generate code that appropriately moves about the stack.

Why do we need to put private members in headers?

But is there any reason to declare private functions in the class definition?

The alternative would be essentially the pimpl idiom but without the superfluous indirection.

Is this language feature more than a historical error?

Best Answer

Private member functions may be virtual, and in common implementations of C++ (that use a vtable) the specific order and number of virtual functions is required to be known by all clients of the class. This applies even if one or more of the virtual member functions is private.

It might seem that this is like "putting the cart before the horse", because compiler implementation choices shouldn't affect the language specification. However, in reality the C++ language itself was developed at the same time as a working implementation (Cfront), which used vtables.