Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!uwvax!gjetost.cs.wisc.edu!solomon From: solomon@gjetost.cs.wisc.edu (Marvin Solomon) Newsgroups: comp.lang.c++ Subject: Re: information hiding Summary: Why a class specification contains non-public information Message-ID: <7709@spool.cs.wisc.edu> Date: 27 Jun 89 13:09:04 GMT References: <6031@watdcsu.waterloo.edu> <6590164@hplsla.HP.COM> <1421@cbnewsc.ATT.COM> Sender: news@spool.cs.wisc.edu Reply-To: solomon@gjetost.cs.wisc.edu (Marvin Solomon) Organization: U of Wisconsin CS Dept Lines: 43 There's been some discussion about why the .h file describing a class needs to include information about the private part of the class, and whether that's a good thing. I remember when I first read about Ada, I found it strange that a package *specification* contained information about the hidden parts of the package. On reflection, I figured out the justification. It's simple once you see it, but perhaps not obvious, especially to those who are not compiler experts. The trouble is that a class definition serves two purposes: to document the class interface to a human user and to provide a compiler with enough information to compile a client of the class. The private members are superfluous (indeed, it could be argued they are harmful) for the former purpose, but essential for the latter. Consider: someclass.h: class SomeClass { public: int visible; private: char hidden[10]; }; client.c: #include "someclass.h" Someclass arr[15]; ... arr[1].visible = 17; // movl #17,arr+16, assuming fullword alignment To compile client.c, the compiler needs to know the size of a SomeClass. I can think of no straightforward implementation-independent way of conveying this information other than to include the "private" section in someclass.h. The C++ language goes to some pains to ensure that the client programmer can't "use" the extra info. For example cout << arr[1].hidden; is an error. But a sufficiently "clever" hacker might *abuse* the information: printf("%s",&(arr[1].visible)+1); Such programmers get what they deserve. -- Marvin Solomon Computer Sciences Department University of Wisconsin, Madison WI solomon@cs.wisc.edu, ...seismo!uwvax!solomon