Operator == with double dispatch in C ++

How to implement

operator==(const Base& base)

to compare subclasses of st, calls will be correctly sent when called

Base* base1 = new Derived1();
Base* base2 = new Derived2();
base1->operator==(*base2)?
+3
source share
2 answers
  • Execute the == operator as a function of free standing.
  • Ask him to call a virtual method for one of the arguments (for example, IsEqual ())

It brings you to what you have.

Derived1::IsEqual(const Base& base)

Called. From here you have several options

  • Use RTTI for dynamic_cast <> base to Derived1
  • If the number of derivatives is small and of course you can implement

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

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

+6
source

++ , ==. , , , , dynamic_cast

+1

Source: https://habr.com/ru/post/1756925/


All Articles