const and non-const member function

Chris Nicholson-Sauls ibisbasenji at gmail.com
Wed Jul 25 12:40:01 PDT 2007


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.  :)

(I'm also not 100% pleased with the 'const R M(){}' syntax for declaring 
const methods...  To me it reads as a function M() returning 'const R'. 
  Yes I know the syntax for that is 'const(R) M(){}' and no I don't have 
a better idea right off hand.  I don't care for the C++ 'R M() const {}' 
either.  Wasn't there something like 'R M:const(){}' volleyed back when 
the const discussions first happened?)

-- Chris Nicholson-Sauls


More information about the Digitalmars-d-learn mailing list