const/invariant

Derek Parnell derek at nomail.afraid.org
Tue Dec 4 23:30:37 PST 2007


On Wed, 5 Dec 2007 06:46:21 +0000 (UTC), Denton Cockburn wrote:

> given a class:
> 
> class C {}
> 
> what's the difference between:
> 
> const C c = new C;
> and
> invariant C c = new C;
> 
> From what I can see, neither are modifiable.  So what's different 
> (D2.008)?

Dunno, except that you have to say ...

 const C c = new C;
 invariant C d = cast(invariant Foo)new C;


And what I don't get is why would anyone bother with const/invariant for
classes since you can't invoke any member functions when you do.

--------------
class Foo
{
    int mbr;

       this() { mbr  = 6174; }
    int get() {return mbr; }
}

void main()
{
    const     Foo c = new Foo();
    int a;
    
    a = c.get();
}

    
    
--------------
I get the error messages ...

  : function test.Foo.get () does not match parameter types ()
  : Error: c.get can only be called on a mutable object, not const(Foo)

Aside from the useless message text "function test.Foo.get () does not
match parameter types ()" that doesn't actually tell me the problem is, I
can't see why this is forbidden. I can see that get() doesn't change
anything but the compiler still will not let me call it. 

So if one can't call any member function in the const object, what is the
point of it? Sure I can cast the const away but why would I want to do that
for every invocation of a member function? I really don't get the point of
const objects when implemented this way.

I thought it might be a way to tell the compiler that I can't call member
functions that happen to change member values. That would make sense to me.

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
5/12/2007 6:20:05 PM


More information about the Digitalmars-d-learn mailing list