www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Return const object through mutable Object

reply Jacob Carlborg <doob me.com> writes:
class Foo
{
     Foo f;

     Foo bar () const
     {
         return f;
     }
}

The above code results in the compile error:

Error: cannot implicitly convert expression (this.f) of type const(Foo) 
to test.Foo

But if I change "bar" to:

Object bar () const
{
     return f;
}

I don't get any errors. Is the last example supposed to compile?

I'm using DMD v2.059.

-- 
/Jacob Carlborg
Apr 15 2012
parent reply Jonathan M Davis <jmdavisProg gmx.com> writes:
On Sunday, April 15, 2012 17:57:27 Jacob Carlborg wrote:
 class Foo
 {
      Foo f;
 
      Foo bar () const
      {
          return f;
      }
 }
 
 The above code results in the compile error:
 
 Error: cannot implicitly convert expression (this.f) of type const(Foo)
 to test.Foo
 
 But if I change "bar" to:
 
 Object bar () const
 {
      return f;
 }
 
 I don't get any errors. Is the last example supposed to compile?
 
 I'm using DMD v2.059.

It definitely looks like a bug. Whether it returns Foo or Object should have no effect on constness, and since f is a member variable of Foo, and the this pointer/reference is const, bar is going to have to return a const reference to it, which the second version isn't doing. - Jonathan M Davis
Apr 15 2012
parent Jacob Carlborg <doob me.com> writes:
On 2012-04-16 02:33, Jonathan M Davis wrote:

 It definitely looks like a bug. Whether it returns Foo or Object should have no
 effect on constness, and since f is a member variable of Foo, and the this
 pointer/reference is const, bar is going to have to return a const reference
 to it, which the second version isn't doing.

 - Jonathan M Davis

This is what I expected. I've reported a bug: http://d.puremagic.com/issues/show_bug.cgi?id=7920 -- /Jacob Carlborg
Apr 15 2012