+5 votes
by (13.6m points)

I'm just writing my first objected oriented project at my univeristy. I found difficulty in overloading == operator. In my base class Organism I have

friend bool operator==(const Organism &curr, const Organism &other);
bool operator==(const Organizm &curr, const Organizm &other) {
    if (curr.x == other.x) {
        if (curr.y == other.y)
            return true;
    }
    return false;
}

Animal inherits from Organism, Fox and Wolf inherits from Animal. When i try to compare

    Fox f(1, 2);
    Wolf w( 1, 2);
    Organizm *o1, *o2;
    o1 = &f;
    o2 = &w;
    bool ok = (o1 == o2);

The comparision return false, even though proper variables are equal. I need operator== for std::find, because I keep all my organisms in std::vector.

3 Answers

+4 votes
by (13.6m points)

You're not comparing those objects, and your operator is not even being invoked.

You are comparing pointers to those objects. Obviously that comparison will always fail as two objects cannot exist in the same place at the same time.

I imagine you meant to write either of the following:

Fox f(1, 2);
Wolf w(1, 2);

Organizm* o1 = &f;
Organizm* o2 = &w;

const bool ok = (*o1 == *o2);

or, better:

Fox f(1, 2);
Wolf w(1, 2);

const Organizm& o1 = f;
const Organizm& o2 = w;

const bool ok = (o1 == o2);

or, simply:

Fox f(1, 2);
Wolf w(1, 2);

// implicit conversions are a thing!
const bool ok = (f == w);
0 votes
by (13.6m points)

The problem is that your code does not compare objects; it compares their addresses:

bool ok = (o1 == o2); // Compare address of f to address of w

If you would like to compare objects referenced by pointers, the call should be like this:

bool ok = (*o1 == *o2);
0 votes
by (13.6m points)

With

Organizm *o1 = &f;
Organizm *o2 = &w;
bool ok = (o1 == o2);

Your are comparing pointers

you want

bool ok = (*o1 == *o2);

to compare objects using your custom operator.

...