Thread overview | ||||||
---|---|---|---|---|---|---|
|
April 13, 2013 class constructor | ||||
---|---|---|---|---|
| ||||
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 Re: class constructor | ||||
---|---|---|---|---|
| ||||
Posted in reply to gedaiu | 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 Re: class constructor | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nicolas Guillemot | 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 Re: class constructor | ||||
---|---|---|---|---|
| ||||
Posted in reply to Nicolas Guillemot | Nicolas Guillemot:
> Classes are instanciated with new, structs are not.
structs are created with new if you want them on the heap.
Bye,
bearophile
|
Copyright © 1999-2021 by the D Language Foundation