Thread overview
class constructor
Apr 13, 2013
gedaiu
Apr 13, 2013
Nicolas Guillemot
Apr 13, 2013
gedaiu
Apr 13, 2013
bearophile
April 13, 2013
Hi,

Why in D this expression does not call the class constructor?

class A {

    int myVal;

    this(int val) {
       myVal = val;
    }

}


int main() {
   A myA = 8;
}


I would like to have a feature like this, because i want to create my own data type. I think it's possible, but i don't know why... std.variant, can be initialized like this.

Thanks!
April 13, 2013
Classes are instanciated with new, structs are not. The following program compiles:

class A {
	int myVal;

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

struct B {
	int myVal;

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

void main() {
	A myA = new A(8);

	B myB = 8;
}
April 13, 2013
On Saturday, 13 April 2013 at 07:57:30 UTC, Nicolas Guillemot wrote:
> Classes are instanciated with new, structs are not. The following program compiles:
>
> class A {
> 	int myVal;
>
> 	this(int val) {
> 		myVal = val;
> 	}
> }
>
> struct B {
> 	int myVal;
>
> 	this(int val) {
> 		myVal = val;
> 	}
> }
>
> void main() {
> 	A myA = new A(8);
>
> 	B myB = 8;
> }

Thanks!
April 13, 2013
Nicolas Guillemot:

> Classes are instanciated with new, structs are not.

structs are created with new if you want them on the heap.

Bye,
bearophile