Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!spool.mu.edu!agate!linus!linus!mbunix!mmk From: mmk@d62iwa.mitre.org (Morris M. Keesan) Newsgroups: comp.lang.c++ Subject: Re: Read-only data access Message-ID: Date: 13 Jun 91 21:18:41 GMT References: <1654@balrog.ctron.com> Sender: news@linus.mitre.org (News Service) Organization: The Mitre Corp., Bedford, MA. Lines: 58 In-Reply-To: bangrazi@ctron.com's message of 13 Jun 91 19:07:14 GMT Nntp-Posting-Host: d62iwa.mitre.org In article <1654@balrog.ctron.com> bangrazi@ctron.com (Anthony Bangrazi) writes: >Could someone please help me? I want to allow read-only access to private >data members, without having a method to return the value (thus avoiding the >parenthesis). > > class Z { > public: > const int& z = &zP; > private: > int zP; > } > > int main () > { > Z* myZ = new Z; > printf ("%d\n", myZ.z); > delete myZ; > } > > **************************** > > Note no parenthesis on "myZ.z" > Also, since z is "const", one cannot "myZ.z = 4" Here's one way to write C++ which doesn't look like C++ (why else want to avoid the parentheses?), and without the need for extra data members: class Z { private: int zP; public: int zpub(void) { return zP; } } #define z zpub() int main() { Z* myZ = new Z; printf ("%d\n", myZ.z); delete myZ; } Note no parentheses, myZ.z is not an lvalue, and we haven't used an extra data member. But what's wrong with printf("%d\n", myZ.z()); ? (Assuming no #define, and z in place of zpub, above) I think it looks more like C++, and will cause less confusion for other people reading your code, who would otherwise being saying to themselves, "Why didn't he just write an inline member function to retrieve this value?" or "What's the purpose of this silly macro?" -------------------------------------------------------------- Morris M. Keesan, temporarily mmk@d62iwa.mitre.org