Thread overview
the behavior of opAssign
Jan 29, 2018
Sobaya
Jan 29, 2018
Jonathan M Davis
Jan 29, 2018
Simen Kjærås
Jan 29, 2018
Sobaya
January 29, 2018
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?
January 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

January 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
January 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 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

I have not read https://dlang.org/spec/class.html
In 15.9, there is an explanation about it.
Sorry.

--
  Sobaya