class instance construction

Daniel Gibson metalcaedes at gmail.com
Thu Nov 11 08:57:40 PST 2010


spir schrieb:
> 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);
> 

Is this really a common case?
Constructing an object, just to call *one* method on it and then throw it away?

> 
> 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...
> 

Again: Is that a common case? A constructor (probably with multiple arguments) 
that all just set the corresponding fields of the object?
However, I agree that all that this.i = i; is tedious.
As I have suggested before in another thread (and Simen did in this thread), 
something like

this( int this.i, float this.y, Foo f) {
     // f is no field of the class.
     this.b = new Bar(f, i);
}

would be helpful because you could mix arguments that are just passed with 
arguments you want to use in the constructor without too much writing overhead.

Cheers,
- Daniel


More information about the Digitalmars-d mailing list