Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of the Java equals method in c++?

Is there something like Java equals()? To compare if object is the same type ?

public boolean equals(Object obj) {
    if (obj == null || !(obj instanceof ViewMode)) {
        return false;
    }

    ViewMode dm = (ViewMode) obj;
    return dm.width == w
        && dm.h == h
        && dm.b == b
        && dm.f == f;
}

public int hashCode() {
    return w ^ h ^ f  ^ b ;
}
like image 694
user63898 Avatar asked Jun 11 '12 13:06

user63898


2 Answers

For the idiomatic equivalent of your example, you would define operator== as follows:

friend bool operator==(const ViewMode &lhs, const ViewMode &rhs) {
    return (lhs.w == rhs.w) && the rest;
}

friend bool operator!=(const ViewMode &lhs, const ViewMode &rhs) {
    return !(lhs == rhs);
}

In C++ you don't normally write a function to allow ViewMode objects to be compared with something that has nothing at all to do with ViewMode. I suppose that if you really wanted that comparison to return false, rather than refusing to compile, then you could add a couple of template operators (as free functions, outside the class):

template <typename T>
bool operator==(const ViewMode &, const T&) {
    return false;
}

template <typename T>
bool operator==(const T &, const ViewMode&) {
    return false;
}

but I really don't recommend it. That Java idiom doesn't apply to C++, because in C++ you pretty much should never have an object, but have no idea of its type.

If you want your equals function to be virtual, then it's probably best to write an equals() virtual function, rather than using operator== for it. You'd write it to take a const ViewObject & as parameter, so no need for any equivalent to the instanceof check. Which is just as well, because C++ does not have any way to take an object of totally unknown type and test whether it is an instance of a specified type.

You rarely need a polymorphic equals function in C++, but if you were using it for example in std::unordered_map, then you'd specify the extra template parameters to the unordered_map. Give it an equality comparison function that takes two pointers and calls equals on one or the other, and a hash function that does something sensible.

like image 81
Steve Jessop Avatar answered Sep 23 '22 02:09

Steve Jessop


You might be able to use the typeid operator for this.

like image 37
Some programmer dude Avatar answered Sep 25 '22 02:09

Some programmer dude