www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Returning this from a const member

reply Robert Clipsham <robert octarineparrot.com> writes:
According to http://digitalmars.com/d/2.0/const3.html:
----
Const member functions are functions that are not allowed to change any 
part of the object through the member function's this reference.
----

With the following code:
----
class Foo
{
	Foo myFoo() const
	{
		return this;
	}
}

void main()
{
	auto f = new Foo;
}
----
I get the error:
----
test.d(5): Error: cannot implicitly convert expression (this) of type 
const(Foo) to test.Foo
----

Why is this? myFoo() isn't changing any part of Foo, so it should be 
fine according to the spec... Or is const like immutable here where it 
causes the rest of the object to become const if one member function is? 
If it is then maybe the spec should be updated to clarify this?
Mar 20 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
Robert Clipsham:
 Why is this?
It's not a hard question. This code compiles: class Foo { const(Foo) myFoo() const { return this; } } void main() { auto f = new Foo; } It's just in a const function the "this" is const, so if you want to return it, then you have to use a "const Foo" type, because it's not a mutable Foo :-) Bye, bearophile
Mar 20 2010
parent Robert Clipsham <robert octarineparrot.com> writes:
On 21/03/10 00:18, bearophile wrote:
 Robert Clipsham:
 Why is this?
It's not a hard question. This code compiles: class Foo { const(Foo) myFoo() const { return this; } } void main() { auto f = new Foo; } It's just in a const function the "this" is const, so if you want to return it, then you have to use a "const Foo" type, because it's not a mutable Foo :-) Bye, bearophile
Now you say it, that does seem obvious, thank you :)
Mar 20 2010