3

How should one implement

operator==(const Base& base)

to compare subclasses s.t. the calls would be properly dispatched when called as

Base* base1 = new Derived1();
Base* base2 = new Derived2();
base1->operator==(*base2)?
Philipp
  • 48,066
  • 12
  • 84
  • 109
MAG
  • 85
  • 8

2 Answers2

7
  1. Implement operator== as a free standing function.
  2. Have it call a virtual method on one of the arguments (e.g. IsEqual())

That gets you to the point where you have

Derived1::IsEqual(const Base& base)

Called. From here you have some options

  1. Use RTTI to dynamic_cast<> base to Derived1
  2. If the number of derived is small and finite, you can implement

    virtual bool Base::IsEqualToDerived(const Derived1& d) {return false};
    virtual bool Base::IsEqualToDerived(const Derived2& d) {return false};
    

as virtual methods. In Derived1, you override and compare for real.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192
1

This seems like a generic C++ question on classes and type rather than a specific question on the operator== . Up to my knowledge, in the particular example you are giving there is no other way but to use dynamic_cast

rodrigob
  • 2,891
  • 3
  • 30
  • 34
  • 2
    You can (and probably should) do it without dynamic_cast using virtual functions. –  Jul 28 '10 at 13:00
  • Well it depends is the issue about base1 receiving the proper call or being able to tell that the input argument is Derived2 instead of just Base ? The first will be solved using virtual function (I agree), the second, using dynamic_cast – rodrigob Jul 28 '10 at 13:38