[LC++]How to use const member functions correctly?
carlo at alinoe.com
Sun Sep 23 09:35:06 UTC 2001
On Sat, Sep 22, 2001 at 11:00:15PM +0200, Davide Bolcioni wrote:
> Your suggestion
> assert(&arg != this);
> seems entirely appropriate for const member functions taking a
> modifiable reference or pointer argument to their type (or an
> ancestor, I guess) just to guard against this surprise.
I don't think that is necessary.
The trick of `const'-ness is that is works fully automatic
without the need of supervision by a human.
There cannot be a surprise because you shouldn't *expect*
anything regarding `c1' when calling c1.f(); where f is
const. Doing so is thinking procedural. When you think
Object Oriented then objects that are const will not be
changed and objects that are not const can be changed.
The compiler will protect that using `const' qualifiers,
but you don't have to realize whether f() is const or
not; not at the moment you CALL it anyway.
If you call
and that changes c2, then ok... that is allowed when c2 is
not const. Whether c1 and c2 are the same object is irrelevant,
whether f() is const or not is also irrelevant (it is only
used by the *compiler*, to warn you when you do something wrong).
Carlo Wood <carlo at alinoe.com>
More information about the tuxCPProgramming