class instance construction

spir denis.spir at gmail.com
Thu Nov 11 01:02:15 PST 2010


Hello,


First, what is the actual point of "new"? I find this keyword rather helpful in that it reminds me the element is referenced/heap-allocated/GC'ed. But is there any ambiguity on the language's side? We cannot construct a class instance in any other way, AFAIK, and "calling" a class can hardly have any other sense. Maybe classes' opCall could be set to the creation routine (whatever new calls); then we would get a single object-creation syntax.
This is no request :-) I just ask to try & understand the rationale behind "new".

Note that this pattern is also a kind of literal notation for anonymous objects, which leads to rather obfuscated expression of the form:
	c = new C(new C1(p1), new C2(p2)), new C3(p3));

Still, an other case when "new" annoys me is method chaining, because it makes syntax heavier and less readable:
	c = (new C(p)).do(x);
versus:
	c = C(p).do(x);
Or, maybe, the parser could be clever enough to correctly decode:
	c = new C(p).do(x);



Second, could there be a default constructor for classes, like for structs? Namely, one that sets declared fields:
	class C {int i;}
	...
	auto c = new C(1);
This is one great advantage of static languages, that the compiler knows more thank to declarations. Isn't it sensible to use this knowledge when helpful? I simply find the following stupid (I mean it's job for a machine, not for a programmer):
	class C {
	    int i;
	    this (int i) {this.i = i;}
	}
As we already enjoy this feature for structs...


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list