Constructor params with same name as members

Shriramana Sharma via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Oct 22 22:03:53 PDT 2014


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) {}
} ;
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 ஶ்ரீரமணஶர்மா श्रीरमणशर्मा



More information about the Digitalmars-d-learn mailing list