Default initialization for classes

Kirk McDonald kirklin.mcdonald at gmail.com
Sat May 20 00:40:30 PDT 2006


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



More information about the Digitalmars-d mailing list