digitalmars.D.learn - Constructor params with same name as members
- Shriramana Sharma via Digitalmars-d-learn (25/25) Oct 22 2014 Hello. Please see the following code:
- Steven Schveighoffer (19/42) Oct 23 2014 This is not the same. In the above, the x outside the parens is ALWAYS a...
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: struct Pair { int x, y ; Pair(int x, int y) : x(x), y(y) {} } ; 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? -- Shriramana Sharma ஶ்ரீரமணஶர்மா श्रीरमणशर्मा
Oct 22 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: 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
Oct 23 2014