const member function synatx?

im no at body.com
Fri Feb 15 15:50:33 PST 2008


I read the page: http://www.digitalmars.com/d/2.0/const3.html
under section "Const Member Functions"

It didn't give any example, but following the example of 'invariant', it
should be:

const ReturnType memberFunc(param) {}

I think this is really confusing: is 'const' trying to specify the
'ReturnType' or the memberFunc?

And if I want to specify both, then I have to write:

const const ReturnType  memberFunc(param) {}, or
const const(ReturnType) memberFunc(param) {}

The 2 leading const in a row looks ugly and confusing.

Why not just use the C++'s postfix syntax for const member function? to put
'const' after the param, and before the body {}

ReturnType memberFunc(param) const {}

So I tried it (although undocumented); and to my glad, it worked (see code below).

But there seems to have a semantic bug: I'm modifying class field in void f(A
o) const {...}, but the compiler didn't complain about it.

I think we should fix the confusing syntax, and use C++'s postfix syntax for
const member function; and also fix this bug.


$ cat const.d
===============================
class A{
public:
  A m_a;
}

class B{
public:
  A m_a;
  A a() const {
    return m_a;
  }
  void f(A o) const {  // without 'const' won't compile
    m_a = o;           // BUG, I'm modifying m_a
  }
/*
  const A v() {
    m_a = null;
    return m_a;
  }
*/
}

int main() {
  const B b = new B();

  A a = b.a();
  a.m_a = null;
  b.f(a);
//b.v();

  return 0;
}
===============================
$ dmd.exe const.d
d:\project\dmd\bin\..\..\dm\bin\link.exe const,,,user32+kernel32/noi;




More information about the Digitalmars-d mailing list