implementing operator== when using inheritance

Add a virtual function int Compare(const Person& rPerson) and use that in your operators


What you want to do is essentiall "virtualize" the comparison operator.

Since operators cannot be virtual (operators can be virtual), you will need to delegate it to something else. Here's one possible solution.

class Person
{
   public:
      /* ... */
      bool operator==(const Person& rhs)
      {
         return m_Name == rPerson.m_Name && this->doCompare(rhs);
      }
   private:
      virtual bool doCompare() = 0;
   };
}
class Employee : public Person
{
   /* ... */
   private:
      virtual bool doCompare(const Person& rhs)
      {
         bool bRetval = false;
         const Employee* pRHSEmployee = dynamic_cast<const Employee*>(&rhs);
         if (pEmployee)
         {
            bRetval = m_Id == pRHSEmployee->m_Id
         }
         return bRetval;
      }
};

The question didn't make clear whether Person needs to be a concrete class. If so, you can make it not pure-virtual, and implement it to return true.

This also uses RTTI, which you may or may not be happy with.

Tags:

C++