const method and return type

Andrea Fontana nospam at example.com
Fri Dec 13 16:09:02 PST 2013


I read:

Const Member Functions
Const member functions are functions that are not allowed to 
change any part of the object through the member function's this 
reference.

I'm not changing anything. Just returning it.

Is this a try to avoid something like the following, then?

... B getter() const { return this.b; }
... void getter2() const { B var = getter(); 
var.non_const_method(); }

I don't think it's the right way, is it?
getter2() shouldn't be allowed becouse var is a reference to 
this.b, that's ok. But enforcing constness of return type IMHO is 
wrong.

Something like:

void main()
{
    B value = myclass.getter();
    b.non_const();
}

seems correct to me. Also this seems correct:

void getter2() /*non-const*/ { getter().non_const_method(); }



On Saturday, 14 December 2013 at 00:01:31 UTC, Adam D. Ruppe 
wrote:
> On Friday, 13 December 2013 at 23:46:14 UTC, Andrea Fontana 
> wrote:
>> class A
>> {
>>    auto getter() const
>>    {
>>        return property;
>>    }
>>
>>    int property = 0;
>>
>> Why this method return "const int"?
>
> Inside getter, "this" is const. Due to transitive const, all 
> the members through this are const too.
>
> So inside getter, property is a const int. The auto return 
> value returns the *exact* type, thus const.


More information about the Digitalmars-d-learn mailing list