In a question regarding the use of typeid
is C++, I suggested it could be used to compare types in objects comparison. I haven't seen it done much, but I had Java's equals
in mind.
Looking into Java a bit more, this seems to be the case: Some say the actual classes of the two objects should be compared, and some say instanceof
is the right tool to use, possibly with double dispatch. There are of course cases in which one of the two is definitively more suitable, but at least both options are considered.
In C++, OTOH, I could barely find code in which the actual types are compared. On most cases, double dispatch is used (with dynamic_cast
), and I couldn't find anyone insisting a quick type comparison is the right thing to do at the beginning of the equality check.
I'm wondering why the problem of polymorphic type comparison has two acceptable solutions in Java, while in C++ only one seems to be considered the best practice? Are there significant technical differences, or just different approaches?
Note: My claims are based on impression, not concrete knowledge. If they are wrong and Java and C++ are indeed similar in that aspect - or different for reasons other than the above, it will obviously be an acceptable answer.
==
can be overloaded - so it depends on the context... – Rozierequals
can be overridden. Not much difference there. – Panaggiooperator==
method. If a class needs the capability, it must overload theoperator==
method. – Imbecility