Why are private variables described in the publicly accessible header file

language-featuresprogramming-languages

OK, so hopefully this is a subjective enough question for Programmers, but here goes. I am continuously broadening my knowledge of languages and software engineering practices… and I've run into something that just makes no sense to me whatsoever.

In C++, class declarations include private: methods and parameters in the header file, which, theoretically, is what you pass to the user to include if you make them a lib.

In Objective-C, @interfaces do pretty much the same thing, forcing you to list your private members (at least, there's a way to get private methods in the implementation file).

From what I can tell, Java and C# allow you to provide an interface/protocol which can declare all the publicly accessible properties/methods and gives the coder the ability to hide all implementation details in the implementation file.

Why? Encapsulation is one of the main principles of OOP, why do C++ and Obj-C lack this basic ability? Is there some kind of best-practices work-around for Obj-C or C++ that hides all implementation?

Thanks,

Best Answer

The question is whether the compiler needs to know how large an object is. If so, then the compiler has to know about the private members in order to count them up.

In Java, there's primitive types and objects, and all the objects are allocated separately, and the variables containing them are really pointers. Therefore, since a pointer is a fixed-size object, the compiler knows how big a thing a variable represents, without knowing the actual size of the pointed-to object. The constructor handles all of that.

In C++, it's possible to have objects represented locally or on the heap. Therefore, the compiler needs to know how big an object is, so that it can allocate a local variable or array.

Sometimes it's desirable to divide class functionality into a public interface and a private everything else, and that's where the PIMPL (Pointer to IMPLementation) technique comes in. The class will have a pointer to a private implementation class, and the public class methods can call that.