Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!dimacs.rutgers.edu!aramis.rutgers.edu!paul.rutgers.edu!carroll From: carroll@paul.rutgers.edu (V. I. Lenin) Newsgroups: comp.lang.c++ Subject: Re: const member functions: why bother the programmer? Message-ID: Date: 24 Jul 90 22:35:12 GMT References: <2026@kulcs.kulcs.uucp> <333@taumet.com> Organization: Rutgers Univ., New Brunswick, N.J. Lines: 44 herman@kulcs.uucp (Herman Moons) asks: >Why does the C++ language demand that the programmer states which >member functions are const? 1. For all the same reasons you declare the "const" in the following: void f(const T *); 2. Because classes have both abstract state and concrete state. In line with the constant goal of raising the level of abstraction in programs, the "const" keyword on a member function should always be used to mean "this member function does not change the abstract state of the object." Unfortunately, C++ defines "const" to mean "this member function does not change the concrete state of the object." (Cfront isn't dumb, it simply has no way of knowing what the "abstract state" of your class is.) Since it is possible for a member function to change the concrete state of an object without changing the abstract state, in order to implement the desired (abstract) meaning of const, the programmer must use a cast in such situations: class T { int i; public: T(); void f() const; // means f doesn't change abstract state }; void T::f() const { // ... T *This = (T*)this; ++This->i; // ... } Here T::i is a data member whose value doesn't functionally affect the abstract state of T. Notice that the above cast is guaranteed to work, since C++ mandates that classes with constructors be placed in writable store. -- martin