Default initialization for classes

Hasan Aljudy hasan.aljudy at gmail.com
Sat May 20 02:39:25 PDT 2006


Kirk McDonald wrote:
> I am slightly confused. As an exercise, I am writing a simple 3D vector 
> class. Part of this involves playing with operator overloading. Here's 
> some of the class:
> 
> class Vector3D {
> public:
>     real x, y, z;
> 
>     this(real x, real y, real z) {
>         this.x = x;
>         this.y = y;
>         this.z = z;
>     }
>     this() { this(0, 0, 0); }
> 
>     Vector3D opAdd(Vector3D r) {
>         return new Vector3D(x + r.x, y + r.y, z + r.z);
>     }
> }
> 
> This was my first stab at the opAdd function, and I think it looks most 
> right. In poking around dsource, I have also seen such functions written 
> like:
> 
>     Vector3D opAdd(Vector3D r) {
>         Vector3D v;
>         v.x = x + r.x;
>         v.y = y + r.y;
>         v.z = z + r.z;
>         return v;
>     }
> 
> (The example I'm thinking of is seen here:
> http://www.dsource.org/projects/tutorials/wiki/CurrencyExample
> )
> 
> So, where's v here? Is D implicitly doing "new Vector3D()"? Is this 
> better, worse, or not different compared to what I did? Where is this 
> mentioned in the spec? (I couldn't find it.)
> 
> -Kirk McDonald


This only works with sturcts. As Oskar said, structs don't need to be 
newed, they are by value.

Now that I look at 
http://www.dsource.org/projects/tutorials/wiki/CurrencyExample
I see that it's doing it on a class! The code must be borken.




More information about the Digitalmars-d mailing list