HP3000-L Archives

December 2004, Week 3

HP3000-L@RAVEN.UTC.EDU

Options: Use Monospaced Font
Show Text Part by Default
Show All Mail Headers

Message: [<< First] [< Prev] [Next >] [Last >>]
Topic: [<< First] [< Prev] [Next >] [Last >>]
Author: [<< First] [< Prev] [Next >] [Last >>]

Print Reply
Subject:
From:
Larry Liska <[log in to unmask]>
Reply To:
Larry Liska <[log in to unmask]>
Date:
Sun, 19 Dec 2004 10:02:58 -0600
Content-Type:
text/plain
Parts/Attachments:
text/plain (41 lines)
 Keven Miller wrote:
> ...
> I'm looking at a class definition with a method
> declared twice. With the only difference, the word const.
> Can you tell me why or whats going on and why I would do this?
>
> class name:public other {
> public:
>         virtual bool isOpen() const;
>         virtual bool isOpen (void);
 > ...
In your example, the object itself is not const, just the method.  I
believe in this case, const applies to the bool return type--it returns
an immutable return value.  This is a design/architecture thang.  If you
are instantiating an object only to query its properties, or calling a
method only to get a value you won't modify, the gurus say you should
use a const object/method.  Then, a year later when a maintenance coder
tries to make a change that alters the object instance/value, they will
get a compiler error since the object/value is const, forcing them to
rethink their code change, and protecting the conceptual integrity of
the design.  "Hey, this value is protected--you can't change it in this
module, only in the foo module. Changing it here will corrupt the
database!"  It is a way of enforcing design "contract".

That is all well and good, I guess.  However, I've run into one or two
situations where "creeping constness" caused no end of trouble, causing
me to have to "cast away constness". My changes were appropriate and
non-breaking, but the class designer only provided const methods.  So, I
had to use a hack to do what I needed to do.  My feeling is that
providing const and non-const versions of a method is a pragmatic
solution, since it puts the onus on the coder to understand the
implications.  If you use the non-const method, you know that the
"contract" is weaker and that the compiler won't protect you as much.
(This pragmatic approach has the downside of duplicating methods, that
differ only in constness...)

lcl

* To join/leave the list, search archives, change list settings, *
* etc., please visit http://raven.utc.edu/archives/hp3000-l.html *

ATOM RSS1 RSS2