Simple operator overload in D language throws exception

Tag: exception , operator-overloading , d Author: liyan618 Date: 2012-03-03

This code:

class C 
{
    int opAdd(C b) { return 1; }
    private int j;
}

void main() 
{
    C a;
    C c;

    int j = a + c;
}

Throws:

"object.Exception: Access Violate - Read at address 0x0"

Best Answer

Classes in D are reference types. You need to instantiate them:

C a = new C();
C b = new C();

Also, opAdd has been replaced by opBinary!"+" in D2 (see D2 operator overloading).

comments:

Thanks! How would you put a class instance on the stack?
Using emplace from std.conv, or the scoped template from std.typecons.
@DanDonnelly Post a separate question if you want a detailed answer for that. There are ways to do it, but normally you don't. They really don't belong there normally.