www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - class constructor

reply "gedaiu" <szabobogdan yahoo.com> writes:
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!
Apr 13 2013
parent reply "Nicolas Guillemot" <nlguillemot gmail.com> writes:
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;
}
Apr 13 2013
next sibling parent "gedaiu" <szabobogdan yahoo.com> writes:
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!
Apr 13 2013
prev sibling parent "bearophile" <bearophileHUGS lycos.com> writes:
Nicolas Guillemot:

 Classes are instanciated with new, structs are not.
structs are created with new if you want them on the heap. Bye, bearophile
Apr 13 2013