Default initialization for classes

Oskar Linde olREM at OVEnada.kth.se
Sat May 20 03:51:19 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.)

In the latter case, Vector3D seems to be a struct rather than a class, and
as such, it is passed by value and not created with new. See more about the
different semantics of structs and classes in D in the docs.

/Oskar




More information about the Digitalmars-d mailing list