const method and return type
Andrea Fontana
nospam at example.com
Fri Dec 13 16:24:00 PST 2013
Just another thought. If we have:
class B;
struct C;
class A
{
void method() const { ... }
B another_class;
C a_struct;
}
B is just a reference to a object, so method() should not
reassign it. The reference should be const, not the object
itself. method() should be able to call mutable another_class
methods. Am I wrong?
Instead "a_struct" is not a reference, so method() should not
edit it, this makes sense. You can return a copy or a const ref
of a struct-member
On Saturday, 14 December 2013 at 00:09:03 UTC, Andrea Fontana
wrote:
> 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