Returning this from a const member

Robert Clipsham robert at octarineparrot.com
Sat Mar 20 17:13:17 PDT 2010


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?


More information about the Digitalmars-d-learn mailing list