Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!gem.mps.ohio-state.edu!ginosko!uunet!peregrine!ccicpg!cci632!rit!tropix!ur-valhalla!uhura.cc.rochester.edu!rochester!rutgers!dptg!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: const member functions ? Message-ID: <9638@alice.UUCP> Date: 15 Aug 89 14:08:58 GMT References: <6590205@hplsla.HP.COM> <9633@alice.UUCP> <1771@avsd.UUCP> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 95 In article <1771@avsd.UUCP>, daniel@avsd.UUCP (Daniel Edelson) writes: > 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? The motivation is to give `const' consistent semantics. For example: class Foo { private: int x; public: Foo() { x = 0; } void set(int n) { x = n; } int get() { return x; } }; void f() { const Foo a; int n = a.get(); // legal a.set(7); // legal or not? } If `const' is to mean anything useful for class objects, there must be some notion of whether or not calling a member function changes the object. Here, Foo::set() changes the object but Foo::get() doesn't. Because Foo::set() changes the object, you'd like the line marked `legal or not?' to be flagged as an error. But that's impossible in general because the definitions of Foo::set() and Foo::get() might have been separately compiled. Therefore C++2.0 lets you say this: class Foo { private: int x; public: Foo() { x = 0; } void set(int n) { x = n; } int get() const { return x; } }; The `const' in the definition of Foo::get() says that it's OK to call Foo::get() on a constant object. Therefore, { const Foo a; int n = a.get(); // legal a.set(7); // illegal } The line marked `illegal' is illegal because `a' is a const object and Foo::set() can't be called for a constant. > 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? There's no syntax for saying that `this' is a constant pointer. However, assignment to `this' is deprecated; some future version of C++ will uniformly treat `this' as a constant pointer. > How about this? > struct S { > int x; > void cmf() const; > }; OK so far, S::cmf is a member that can be called on a const object. > void put(S *p) { cin >> p->x; } > void look(const S *p) { cout << p->x; } No problems here. > 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" > } Right you are. I'll reiterate, though, that saying `this=this' is a dangerous anachronism and should be avoided and ultimately eliminated. In fact, I'm not sure what purpose it serves if it's not in a constructor or destructor. -- --Andrew Koenig ark@europa.att.com