Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!cs.uoregon.edu!ogicse!orstcs!fog.CS.ORST.EDU!budd From: budd@fog.CS.ORST.EDU (Tim Budd) Newsgroups: comp.lang.c++ Subject: Re: Read-only data access Message-ID: <1991Jun13.211926.20276@lynx.CS.ORST.EDU> Date: 13 Jun 91 21:19:26 GMT References: <1654@balrog.ctron.com> Sender: @lynx.CS.ORST.EDU Organization: Computer Science Department, Oregon State Univ. Lines: 49 Nntp-Posting-Host: fog.cs.orst.edu In article <1654@balrog.ctron.com> bangrazi@ctron.com writes: > >**************************** > >class Z { >public: > const int& z = &zP; >private: > int zP; >} > >int main () >{ > Z* myZ = new Z; > printf ("%d\n", myZ.z); > delete myZ; >} > >**************************** > This is a neat trick. I like it. But I think some of the details are wrong (at least they don't work as planned using GNU 1.37). The declaration needs to be int& const (reference to a constant), not const int & (constant reference). Also G++ doesn't like the constant assignment as shown, but will allow me to put it in the constructor. Here is the example fixed up (at least it works on MY machine). class Z { public: int& const z; Z() : z(zP) { zP = 12; } modifier() { /* methods can modify zP */ zP += 7; } private: int zP; }; int main () { Z* myZ = new Z; printf("%d\n", myZ->z); myZ->modifier(); // myZ->z = 24; will generate an error printf("%d\n", myZ->z); }