Re: operator==
On Dec 15, 5:22 pm, Andrea Crotti <andrea.crott...@gmail.com> wrote:
James Kanze <james.ka...@gmail.com> writes:
I'd do just the opposite:
class Base
{
virtual bool isEqual(Base const& other) const = 0;
public:
bool operator==(Base const& other) const
{
return typeid(*this) == typeid(other)
&& isEqual(other);
}
};
Then override isEqual in all of the derived classes, converting
other to the correct type and doing the comparison.
I don't see the advantage, then I still have to implement the
op== in all my subclasses, which is very redundant and useless
since I already know that they're are equal if all the fields
are equals...
But how do you know that all the fields are equal?
If you want to support comparison for equality in all of the
derived classes, you have to implement some function which
defines equality for those classes. There is no other way;
there is no implicit definition of equality in C++.
If you want to compare for equality over a hierarchy, you also
need to implement the case where the two classes are not the
same. Most of the time (but not always), you can get by with
something like the above, and assume that if the two objects
have different types, they aren't equal. (When you can't, you
need something more complex; some form of double dispatch.)
--
James Kanze