Feature request - simpler constructors
Michel Fortin
michel.fortin at michelf.com
Fri Sep 21 05:47:20 PDT 2007
On 2007-09-21 00:57:01 -0400, "Janice Caron" <caron800 at googlemail.com> said:
> this(int x, int y, int bar):(x,y) //bar is not assigned to anything
> {
> //super constructor calls go here
> //members are assigned here (_after_ calling super)
> //first line of user code goes here
> if (x > 5) {} //refers to member 'x' not parameter 'x'
> }
I think you are illustrating a point of ambiguity in this syntax.
You're saying on the last line that since there's an auto-assignment
before the body 'x' now represents the member variable. I find that
odd, an potentially confusing. I understand why it makes sense, because
once the parameter has been assigned there's generally no need to reuse
it, but you may still want to access the member. Still, I don't like it
since the pretty innocuous thing in the head (the auto-assignment)
changes the standard semantics of the function.
Another confusing thing is that members are not assigned before the
constructor call, despite that assignment being specified way up in the
code.
So I'd like to propose something else. Let's begin with a basic concept
which I call "group-assignment":
this(int x, int y, int bar)
{
this = { x: x, y: y };
if (x > 5) {} // refers to parameter 'x' as usual.
}
The group-assignment "this = {}" would assign values to members using
the same syntax as for statically initializing a struct. The mass
assignment happen exactly where you put it in the code and, in the case
above, is equivalent to writing this:
this.x = x;
this.y = y;
If you need to call super, it can be done either before or after the
assignment (as you can do now with regular assignment). You can also
change one of the variables prior the group-assignment if you wish.
Then, to remove the need to type each variable twice, a shortcut could
be added to that syntax, perhaps like this:
this(int x, int y, int bar)
{
this = { :x, :y };
if (x > 5) {} // refers to parameter 'x' as usual.
}
Basically: if you omit the member name but the value is still preceded
by a colon, and that value is a variable of the same name as the
member, you have an assignment to that member.
Oh, and the group-assigment syntax doesn't need to apply only to
constructors, it can work in all member functions, and really
everywhere if you use something else than 'this' on the left. For
instance:
myPoint = { :x, :y }
would simply read as a shorthand for this:
myPoint.x = x;
myPoint.y = y;
What do you think?
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list