Properties and const

Janice Caron caron800 at googlemail.com
Tue Sep 11 23:51:11 PDT 2007


On 9/11/07, Janice Caron <caron800 at googlemail.com> wrote:
>
> Hi,
>
> the admittedly now out-of-date documentation for const says, of class
> member functions, that the syntax for member functions which do not
> modify member variables should be
>
> invariant void foo()
>
> Does that mean that all "getter" property functions will have to be
> re-prototyped?
>
> As in
>
> class C
> {
>     private int my_x;
>     invariant int x() { return x; }
> }
>
> ?
>



So, if I've understood this correctly, the syntax for a member function
which (a) does not modify any member variables, and (b) returns an invariant
pointer, would be

class C
{
    invariant invariant int * f() { /* body */ }
}

The first "invariant" tells you (a); the second "invariant" tells you (b).
This leads me to conlude that

class C
{
    invariant int * f() { /* body */ }
}

is surely ambiguous. It could be interpreted either as "f is a member
function of C which does not modify any of C's member variables, and which
returns a pointer to int", or "f is a member function of C which is
permitted to modify C's member variables, and which returns an invariant
pointer to int".

It is precisely in order to avoid this ambiguity that C++ syntax has the
"const" at the end, as in

/* C++ */
class C
{
    int * f() const { /* body */ }
    const int * f() { /* body */ }
    const int * f() { /* body */ } const
}

In the above C++ example, the first function declares a member function of C
which does not modify any of C's member variables, and which returns a
pointer to int, while the second function returns a member function of C
which is permitted to modify C's member variables, and which returns a const
pointer to int. And for completeness, the third one declares a member
function of C which does not modify any of C's member variables, and returns
a const pointer to int.

I will freely admit, I don't like C++'s syntax either. The whole "const at
the end" business is confusing. (It's not so confusion now that I've got
used to it, but it was confusing at first). I don't know whether or not D
can do better, but I certainly don't like the idea of declarations being
ambigous.

I have no suggestion for how to fix this, however I bring to your attention
the fact that it might need fixing.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20070912/754ab640/attachment.html>


More information about the Digitalmars-d mailing list