digitalmars.D.learn - the behavior of opAssign
- Sobaya (18/18) Jan 29 2018 I found a strange behavior.
- Jonathan M Davis (5/23) Jan 29 2018 I don't think so. The first "assignment" is actually initialization, not
- Simen =?UTF-8?B?S2rDpnLDpXM=?= (11/28) Jan 29 2018 The first assignment in the constructor isn't actually a call to
- Sobaya (6/37) Jan 29 2018 I have not read https://dlang.org/spec/class.html
I found a strange behavior. class A { void opAssign(int v) {} } class Test { A a; this() { a = new A(); // removing this causes compile error. a = 3; // cannot implicitly convert expression `3` of `int` to `A` } } void main() { // this is allowed. A a; a = 3; } Is it a compiiler's bug?
Jan 29 2018
On Monday, January 29, 2018 09:23:55 Sobaya via Digitalmars-d-learn wrote:I found a strange behavior. class A { void opAssign(int v) {} } class Test { A a; this() { a = new A(); // removing this causes compile error. a = 3; // cannot implicitly convert expression `3` of `int` to `A` } } void main() { // this is allowed. A a; a = 3; } Is it a compiiler's bug?I don't think so. The first "assignment" is actually initialization, not assignment. opAssign is for assigning to a value that was already initialized. - Jonathan M Davis
Jan 29 2018
On Monday, 29 January 2018 at 09:23:55 UTC, Sobaya wrote:I found a strange behavior. class A { void opAssign(int v) {} } class Test { A a; this() { a = new A(); // removing this causes compile error. a = 3; // cannot implicitly convert expression `3` of `int` to `A` } } void main() { // this is allowed. A a; a = 3; }The first assignment in the constructor isn't actually a call to opAssign, it's a constructor call. In the same way, this will not compile: A a = 3; Also, since classes are reference types, you will need to construct an instance before assigning an int to it. The code in your main() will crash at runtime because the 'this' reference is null inside opAssign. -- Simen
Jan 29 2018
On Monday, 29 January 2018 at 10:06:23 UTC, Simen Kjærås wrote:On Monday, 29 January 2018 at 09:23:55 UTC, Sobaya wrote:I have not read https://dlang.org/spec/class.html In 15.9, there is an explanation about it. Sorry. -- SobayaI found a strange behavior. class A { void opAssign(int v) {} } class Test { A a; this() { a = new A(); // removing this causes compile error. a = 3; // cannot implicitly convert expression `3` of `int` to `A` } } void main() { // this is allowed. A a; a = 3; }The first assignment in the constructor isn't actually a call to opAssign, it's a constructor call. In the same way, this will not compile: A a = 3; Also, since classes are reference types, you will need to construct an instance before assigning an int to it. The code in your main() will crash at runtime because the 'this' reference is null inside opAssign. -- Simen
Jan 29 2018