Class Initialization

Vijay Nayar vnayar at wgen.net
Wed Feb 1 11:32:46 PST 2012


The basic idea is that in D, any statically identifiable information 
(known at compile-time), can be used to assign class members as they are 
declared.

Any time a new object is created, it will take those default values 
specified for its members.

This is a small example demonstrating default initialization for both 
structs and classes.  In fact, compared to the version of C++ I used to 
use (I can't speak for C++11), the syntax is far more consistent and less 
verbose than initializer lists.

struct Dummy {
     int field1 = 10;
     int field2 = 11;
}

class MyClass {
     int a = 0;
     int[] b = [1, 2, 3];
     Dummy c = Dummy(4, 5);

     int d = 6;

     this() {
     }

     this(int val) {
         d = val;
     }
}

void main() {
     MyClass first = new MyClass();
     MyClass second = new MyClass(7);

     assert(first.a == 0);
     assert(first.b == [1, 2, 3]);
     assert(first.c.field1 == 4);
     assert(first.d == 6);

     assert(second.c.field1 == 4);
     assert(second.d == 7);
}

You are correct that in the case of the second constructor, two 
assignments effectively take place, d = 6, then d = 7.  However, I do not 
think the compiler can know what you intend to do in the constructor, or 
even that you will not use the default value of d before reassigning it.

In short, I think the optimization would tend to become more of a source 
of problems than a gain in performance in any meaningful way.

  - Vijay

On Tue, 31 Jan 2012, Zachary Lund wrote:

> In C++, they provide a mechanism to initialize class variables to a passed 
> value.
>
> class Test
> {
> 	int bob;
>
> public:
> 	Test(int jessica) : bob(jessica) { }
> };
>
> The above basically says "int this.bob = jessica;" as opposed to this:
>
> class Test
> {
> 	int bob;
> public:
> 	Test(int jessica) { bob = jessica; }
> };
>
> which basically says "int this.bob = void; bob = jessica;". Now, I'm not a 
> speed freak but this is a quick and should be a painless optimization. D 
> allows defaults set by the class but cannot seem to find anything to allow me 
> variable initialization values. Not that it's that big of a deal but am I 
> missing something?
>


More information about the Digitalmars-d-learn mailing list