I’ve always been confused by the fact that most OOP languages (or rather, C++) make you define private methods/members in the interface (by interface I mean the class declaration – seems like I was confused). Isn’t this showing the implementation details of the class and going against the idea of encapsulation?
Is there a good reason for this that I’ve been missing?
For C++ it’s an implementation issue.
The C++ compiler must be able to generate code that uses a class by only seeing the class declaration and not the implementation. One very important thing that is needed by the compiler is the size of an instance of the class because among other things C++ handles sub-objects in objects by embedding and not by storing a reference to a separate object. To be able to build an object (e.g.
struct X { Y y; Z z; }) the size of all sub-objects (e.g.YandZ) must be known in advance.A workaround for this problem is to use the “pimpl” pattern (also named the “compiler firewall” pattern) that allows you to keep all internal details hidden from the users of a class. This unfortunately carries some runtime extra cost with it but most the time it’s a negligible one. With this approach the public object will always have the size of a pointer and all data in the instance will be accessed using an extra indirection… the advantage is that you can add private data members and users of the class don’t need to be recompiled (and if your class is for example in a DLL this allows to maintain even binary compatibility).
Being able to declare just private methods (no data) in the implementation part would have been possible without any added complexity on the compiler, but C++ designer thought it was better to keep one single declaration for a class instead.
Actually even just adding a private method may affect the size of the a class instance in many implementations (e.g. if the private method is the only virtual one in the class).