Re: Writing a polymorphic equals()
On Jul 22, 1:40 pm, kelvSYC <kelv...@gmail.com> wrote:
Suppose I have a class hierarchy as follows:
class Base { // abstract base class
int baseData;
public:
virtual bool equals(const Base&) const;
};
class Derived1 {
//...
};
class Derived2 {
//...
};
Assume that all leaf subclasses of Base implement operator==() and
operator!=() by using the equals() function (actually quite
irrelevant, but still...),
Actually ;-) you don't seem to need equals(). virtual operator== and
operator!= implemented in terms of operator== should do it.
and that any subclass which does not
implement operator==() is abstract. How should I write the subclass
equals() to ensure that if you have two objects of different
subclasses equals() always returns false?
My guess is that objects you're comparing need to be of the exact same
type, and if so you would need to resort to e.g. typeid.
However, comparing objects of different types smells bad any way I
look at it. Doing it really is comparing apples to oranges.
Here: apple and orange are both fruit. What does it mean to ask: "is
this apple equal to that orange?" Probably nothing, not unless you
drill down to a more specific comparison criteria (e.g. are they
equally sweet).
It seems that doing
something such as
bool Derived1::equals(const Base& rhs) const { return false; } //
Do this in every subclass of Base
bool Derived1::equals(const Derived1& rhs) const { return
Base::equals(rhs) && ... ; } // Calling immediate superclass equals()
IMO, that won't work. Base:equals is Base::equals, not
Derived1::equals(const Base&).
If you have inheritance and virtual stuff, it normally means that you
want to use derived types through a reference to base. Any attempt to
wiggle out of that should fail.
is a bit repetitive. Is there a way to modify Base, say, so that
writing the first function in every subclass can be avoided?
(Again, I wouldn't do any of this, but if you really decide to go for
it, then...)
You might do:
class Base
{
protected:
virtual bool equals(const Base& rhs) = 0;
public:
bool operator==(const Base& rhs) // intentionally not virtual.
{
return typeof(this) == typeof(rhs) ? equals(rhs) : false;
}
};
class Derived
{
virtual bool equals(const Base& rhs)
{// Actual same-type-comparison here.}
// Additionally, you __might__ find this beneficial:
private:
bool operator==(const Derived&) {return false;} // you don't want to
ever call this.
};
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]