7.2 Intended use and limitations

Since a class definition is usually contained in a header .h file, both the source code that implements the class and the source code that uses the class can see the definition of a class. In other words, the private members are not exactly completely hidden.

However, because the compiler does not permit any non-member function access the private members, it is relatively safe to have the private members exposed to everyone. In an ideal object-oriented language, private members should not be exposed, at all, to code that is only supposed to use (and not to define) a class.

Note that this limitation stems from the C heritage of C++. Object files from a C and C++ compiler does not include type or class information. Type or class information is available only to the compiler during compile-time, and not available during link-time. This makes it impossible to embed public/private designation in an object file, and defer exposure of public definitions at link-time.

This problem is solved in some other languages. Java, for example, embeds class definition information in its object code (byte-code) files. As a result, there is no need to use header files to expose members of a class. Instead, each source code file indicates which modules it requires. The compiler then locate the compiled byte-code of the requested module, and acquire class definitions from the compiled byte-code file. In other words, the source files that produce the requested byte-code file do not need to be present at all. This also means private members are completely hidden from the user of a class.

Copyright © 2006-09-26 by Tak Auyeung