www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Bypassing the const promise

reply =?ISO-8859-1?Q?Tomek_Sowi=f1ski?= <tomeksowi.getridof this.gmail.and.com.that> writes:
const on a function forbids changing members:

class Wrong {
    int a;
    void foo() const {
        a = 4;
    }
}

The above rightly doesn't compile. But with a little twist...

class A {
    int a;
    void foo(ref int i) const {
        i = 4;
    }
    void foo() const {
        foo(a);
    }
}

void main() {
    auto a = new A;
    a.foo;
    assert(a.a == 4);
}

... I bypass the const promise on a function (two of them in fact). No casting,
no evil stuff.

Is this a compiler bug or feature?

Tomek
Nov 19 2009
next sibling parent div0 <div0 users.sourceforge.net> writes:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Tomek Sowiński wrote:
 const on a function forbids changing members:
 
 class Wrong {
     int a;
     void foo() const {
         a = 4;
     }
 }
 
 The above rightly doesn't compile. But with a little twist...
 
 class A {
     int a;
     void foo(ref int i) const {
         i = 4;
     }
     void foo() const {
         foo(a);
     }
 }
 
 void main() {
     auto a = new A;
     a.foo;
     assert(a.a == 4);
 }
 
 ... I bypass the const promise on a function (two of them in fact). No
casting, no evil stuff.
 
 Is this a compiler bug or feature?
 
 Tomek
That's definitely a bug. Casting away const should always be explicit operation. - -- My enormous talent is exceeded only by my outrageous laziness. http://www.ssTk.co.uk -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iD8DBQFLBaP+T9LetA9XoXwRAjsWAJ4g8F2vShGWRsiOXiqa2ONBr4YMvACeM+UX /M2U4uArNNu3Xb6vGgKoIKc= =+WE+ -----END PGP SIGNATURE-----
Nov 19 2009
prev sibling parent reply Stewart Gordon <smjg_1998 yahoo.com> writes:
Tomek Sowiński wrote:
<snip>
 ... I bypass the const promise on a function (two of them in fact). No
casting, no evil stuff.
 
 Is this a compiler bug or feature?
http://d.puremagic.com/issues/show_bug.cgi?id=3534
Nov 20 2009
parent =?ISO-8859-1?Q?Tomek_Sowi=f1ski?= <just ask.me> writes:
Stewart Gordon Wrote:

 Tomek Sowiński wrote:
 <snip>
 ... I bypass the const promise on a function (two of them in fact). No
casting, no evil stuff.
 
 Is this a compiler bug or feature?
http://d.puremagic.com/issues/show_bug.cgi?id=3534
Thanks!
Nov 20 2009