Maxpm
Maxpm

Reputation: 25592

Why isn't opAssign overloadable for classes?

This D specification table says that assignment overloading is only possible for structs, not classes. This surprises me. Isn't the syntactic sugar of A = B harmless? What was the design rationale for restricting it to structs?

Upvotes: 3

Views: 356

Answers (3)

he_the_great
he_the_great

Reputation: 6784

I would file a bug, and did. The general rule is to follow The D Programming Language by Andrei Alexandrescu, the DMD implementation, and then the website. As I don't have a copy of The D Programming Language handy, I'm going with the DMD implementation on this:

class A {
    int a;
    string b;
    float c;
    
    void opAssign(B b) {
       a = b.a;
    }
}

class B {
    int a;
}
void main()
{
    auto a = new A();
    a.a = 5;
    auto b = new B();
    b.a = 10;
    a = b;

    assert(a.a == 10);
}

Upvotes: 0

BCS
BCS

Reputation: 78633

D classes have reference semantics. If you want a way to get a copy of the object (it think) the standard or conventional thing to do is provide a .dup property.

Upvotes: 4

deadalnix
deadalnix

Reputation: 2325

In D, classes are used by reference. So, when you do A = B, you do not copy the object itself, but just a reference to that object.

None of objects are modified during the process. So it makes no sense to define opAssign for thoses.

Upvotes: 9

Related Questions