| Thread overview | 
|---|
August 20, 2002 invariant | ||||
|---|---|---|---|---|
  | ||||
This should raise an exception, right?
class A {
  int a;
  invariant {
    assert(a>0);
  }
}
void main()
{
  A b;
  b=new A();
  b.a=-2;
}
Besides, if I declare a as private, it still works. Why?
 | ||||
August 21, 2002 Re: invariant | ||||
|---|---|---|---|---|
  | ||||
Posted in reply to Carlos  | "Carlos" <carlos8294@msn.com> wrote in message news:aju78e$1r1o$1@digitaldaemon.com... > This should raise an exception, right? No, the invariant only gets called when a public member function gets called, and after the constructor gets called. There is no constructor declared for A. If you do declare one like: this() { } then the assert will trip. > class A { > int a; > invariant { > assert(a>0); > } > } > > void main() > { > A b; > b=new A(); > b.a=-2; > } > > Besides, if I declare a as private, it still works. Why? Because main() is in the same module as class A, so they are 'friends'. If A is put into a separate module, then you'll get the access violation.  | |||
August 21, 2002 Re: invariant | ||||
|---|---|---|---|---|
  | ||||
Posted in reply to Walter  | Ok. Thanks. "Walter" <walter@digitalmars.com> escribió en el mensaje news:ajv52t$2prk$1@digitaldaemon.com... > > "Carlos" <carlos8294@msn.com> wrote in message news:aju78e$1r1o$1@digitaldaemon.com... > > This should raise an exception, right? > > No, the invariant only gets called when a public member function gets > called, and after the constructor gets called. There is no constructor > declared for A. If you do declare one like: > this() { } > then the assert will trip. > > > class A { > > int a; > > invariant { > > assert(a>0); > > } > > } > > > > void main() > > { > > A b; > > b=new A(); > > b.a=-2; > > } > > > > Besides, if I declare a as private, it still works. Why? > > Because main() is in the same module as class A, so they are 'friends'. If A > is put into a separate module, then you'll get the access violation. > >  | |||
Copyright © 1999-2021 by the D Language Foundation
 
Permalink
Reply