How to Compare 2 objects of the same class

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 3 13:24:44 PDT 2017


On 06/03/2017 10:02 PM, Mark wrote:

> auto A = new Box();
> auto B = new Box();
> 
> if(A.opEquals(B)) {}
> 
> gives the error
> test.o:(.data.rel.ro+0x18): undefined reference to 
> `_D5Stack12__ModuleInfoZ'
> collect2: error: ld returned 1 exit status
> Error: linker exited with status 1

Your code works for me (when adding `class Box {}` and a `main` 
function). An "undefined reference" error can mean that you forgot to 
include a module on the command line.

> if(Object.opEquals(A,B) gives
> 
> test.d(10): Error: function object.Object.opEquals (Object o) is not 
> callable using argument types (Box, Box)

Yeah, that's not how you do it.

> How do I got about comparing two objects then??
> Thanks.

Just use the usual equality operator: `==`. Or if you want to check for 
identity, use the binary `is` operator.

----
class Box {}

void main()
{
     auto A = new Box();
     auto B = new Box();

     if (A == B) {}
     if (A is B) {}
}
----

By default, they act the same. But you can change how `==` behaves by 
overriding `opEquals`. You cannot override `is`.


More information about the Digitalmars-d-learn mailing list