Constructor params with same name as members
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Oct 23 06:39:43 PDT 2014
On 10/23/14 1:03 AM, Shriramana Sharma via Digitalmars-d-learn wrote:
> Hello. Please see the following code:
>
> import std.stdio ;
> struct Pair {
> int x, y ;
> this (int x, int y) { x = x ; y = y ; }
> }
> void main() {
> auto P = Pair(1, 2) ;
> writeln(P.x, ' ', P.y) ;
> }
>
> This outputs 0 0, whereas the equivalent C++ code outputs 1 2 correctly:
>
> # include <iostream>
> struct Pair {
> int x, y ;
> Pair(int x, int y) : x(x), y(y) {}
> } ;
This is not the same. In the above, the x outside the parens is ALWAYS a
member. D does not have this syntax. Change it to the same as your D
implementation, and you get the same result (actually worse, because C++
will not initialize x and y for you).
> int main() {
> auto P = Pair(1, 2) ;
> std::cout << P.x << ' ' << P.y << std::endl ;
> }
>
> It seems to me that D should either not permit argument names to
> shadow the member names, since it has no initializer lists and all
> members are automatically initialized. Comments?
You're missing the "or" part of that statement :)
But 2 things:
x = x;
This should produce an error, or at least a warning I think, as it does
nothing. However, even with dmd -w, it does not. I know I have seen the
compiler complain about noop statements before, I just don't know under
what circumstances
and 2, you would use the same mechanism as you use with C++ to
initialize the items inside the ctor:
this.x = x;
Note, the rules for shadowing are the same as for any function
parameters to any function vs. members or module variables. Nothing is
inconsistent here.
-Steve
More information about the Digitalmars-d-learn
mailing list