const and non-const member function

James Dennett jdennett at acm.org
Wed Jul 25 20:54:25 PDT 2007


Chris Nicholson-Sauls wrote:
> Christian Kamm wrote:
>>> In C++ it is possible to have a const and a non-const member function
>>> with
>>> the same name and parameter types. ...
>>> Is something like this possible in D?
>>
>> I don't think it's possible (yet). Trying
>>
>> class Foo
>> {
>>   void bar() {}
>>   const void bar() {}
>> }
>>
>> gives me an error. I'm not sure if it is by design or just not working
>> yet.
>>
>>> Furthermore, is it possible to overload opApply(...) so it can be called
>>> on non-const objects and const objects, and the non-const variant has
>>> read-write access:
>>
>> Having that would pretty much depend on being able to have a opApply
>> and a
>> const opApply. I tried by using two functions with different names,
>> but the
>> compiler segfaulted on a ref const(Struct*).
>>
>> Cheers,
>> Christian
> 
> I may be wrong, but I think the idea is that a method either is or isn't
> const-safe, and the difference between const and mutable references to
> the object is supposed to be in the availability of methods, not in
> their behavior.  While I'm sure there's some percentage of the time
> subtle behavioral changes could be desirable, I don't believe
> const-method overloading is meant to happen.
> 
> That said, a few demonstrative cases sometimes do wonders.  :)

The normal reason (coming from C++) for having overloads by
constness is when the return value should differ in constness.

The C++ community would frown on code with differences between
const and non-const member functions other than those that
directly relate to constness.

A trivial almost example is any object returning a reference
to a component of itself; if the object is const, then the
reference to its component should not allow modification,
but if the object is non-const, then modification of its
component may well be reasonable.

(There's a separate debate that I don't want to get into about
whether it's poor design to expose references to components.
If that's a sticking point to you, imagine that the relationship
is "uses" rather than "is composed of".)

-- James


More information about the Digitalmars-d-learn mailing list