How to implement operator== for polymorphic classes in c++
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/1691007/whats-the-right-way-to-overload-operator-for-a-class-hierarchy">What’s the right way to overload operator== for a class hierarchy?</a>  </p>
</blockquote>



<p>I have a base class and several derived classes like in the following code:</p>

<pre><code>class Base
{
public:
    friend bool operator==(const Base&amp;, const Base&amp;);
    virtual ~Base(){}

private:
    virtual bool equals(const Base&amp; other) const = 0;
};

bool operator==(const Base&amp; lhs, const Base&amp; rhs)
{
    return lhs.equals(rhs);
}

class A : public Base
{
public:
    A(int x) : x_(x){}

private:
    virtual bool equals(const Base&amp; other) const;
    int x_;
};

bool A::equals(const Base&amp; other) const
{
    const A* pA = dynamic_cast&lt;const A*&gt;(&amp;other);
    if(!pA) return false;
    return x_ == pA-&gt;x_;
}

class B : public Base
{
public:
    B(double y) : y_(y){}

private:
    virtual bool equals(const Base&amp; other) const;
    double y_;
};

bool B::equals(const Base&amp; other) const
{
    const B* pB = dynamic_cast&lt;const B*&gt;(&amp;other);
    if(!pB) return false;
    return y_ == pB-&gt;y_;
}
</code></pre>

<p>To be able to compare two derived classes I want to have operator==. The question is how to achieve this in an object oriented way (e.g. respecting encapsulation, maintainability and extensibility). Are there some recommended patterns to do that? Is there an alternative to the above approach avoiding dynamic_cast?</p>
