Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!gatech!purdue!decwrl!vixie!avsd!daniel From: daniel@avsd.UUCP (Daniel Edelson) Newsgroups: comp.lang.c++ Subject: Re: const member functions ? Message-ID: <1771@avsd.UUCP> Date: 18 Jul 89 22:40:44 GMT References: <6590205@hplsla.HP.COM> <9633@alice.UUCP> Reply-To: daniel@avsd.UUCP (Daniel Edelson) Organization: AMPEX Corporation, Redwood City, CA and UC Santa Cruz Lines: 52 >In article <6590205@hplsla.HP.COM>, jima@hplsla.HP.COM (Jim Adcock) writes: > >> Is there a way to declare a member function const -- IE to tell the compiler >> that the member function does not change the value of this nor *this In article <9633@alice.UUCP> ark@alice.UUCP (Andrew Koenig) responds: > >Yes [in 2.0]: > > class foo { > int n; > public: > void setsize(int k) { n = k; } > int getsize() const { return n; } > }; > >In a member function defined with `const' this way, `this' is >a pointer to a constant object. >-- > --Andrew Koenig > ark@europa.att.com Why is this feature useful? Is it to improve code readability by making it clear when a member function does not alter any member data? Is there also a reliability motivation? RE: jima's other question, is there also a syntax for specifying that `this' is a constant pointer rather than a pointer to a constant object? How about this? struct S { int x; void cmf() const; }; void put(S *p) { cin >> p->x; } void look(const S *p) { cout << p->x; } void S::cmf() const { put(this); // illegal, put() takes a "S *" but `this' is a "const S *" look(this); // legal, look() takes a "const S *", which `this' is this=this; // legal, `this' is of type "const S *", not "S *const" } Is this correct? Daniel Edelson Currently: daniel@avsd.UUCP (Ampex Corporation, Redwood City, CA) And also: daniel@saturn.ucsc.edu (Univ. of Calif., Santa Cruz)