Suppose you have a polymorphic object
class PolyObj
{
public:
virtual ~PolyObj() {}
virtual bool compare(const PolyObj& s) const =0;
....
bool operator==(const PolyObj& s) const
{ return compare(s); }
};
And suppose you have many different implementations ObjA, ObjB, ObjC all derived by PolyObj.
One way to implement
compare
in ObjA can be:
class ObjA: public PolyObj
{
A a;
B b;
public:
virtual bool compare(const PolyObj& s) const
{
const ObjA* pA = dynamic_cast<const ObjA*>(&s); if(!pA) return false; return a == pA->a && b == pA->b; }
};
Providing similar implementation for ObjB and ObjC, you get a polymorphic oprator== for both its operands, just with three functions instead of nine.
Basically we did a "dual dispatch": the first through the V-table, and the second through RTTI.
Of course, we can do it differently (like calling a virtual function of the second object that calls a virtual function of the first), but with much more complex code.
(see
Multimethod[
^])