Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing operator== when using inheritance

Tags:

c++

I have a base class which implements the == operator. I want to write another class, inheriting the base class, and which should reimplement the == operator.

Here is some sample code :

#include <iostream>
#include <string>

class Person
{
public:
  Person(std::string Name) { m_Name = Name; };

  bool operator==(const Person& rPerson)
  {
    return m_Name == rPerson.m_Name;
  }

private:
  std::string m_Name;
};

class Employee : public Person
{
public:
  Employee(std::string Name, int Id) : Person(Name) { m_Id = Id; };

  bool operator==(const Employee& rEmployee)
  {

    return (Person::operator==(rEmployee)) && (m_Id == rEmployee.m_Id);
  }

private:
  int m_Id;
};

void main()
{
  Employee* pEmployee1 = new Employee("Foo" , 1);
  Employee* pEmployee2 = new Employee("Foo" , 2);

  if (*pEmployee1 == *pEmployee2)
  {
    std::cout << "same employee\n";
  }
  else
  {
    std::cout << "different employee\n";
  }

  Person* pPerson1 = pEmployee1;
  Person* pPerson2 = pEmployee2;

  if (*pPerson1 == *pPerson2)
  {
    std::cout << "same person\n";
  }
  else
  {
    std::cout << "different person\n";
  }
}

This sample code give the following result :

different employee
same person

Where I would like, even when handling Person* pointers, to make sure they are different.

How am I supposed to solve this problem ?

Thanks !

like image 359
Jérôme Avatar asked Feb 19 '09 15:02

Jérôme


1 Answers

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.

like image 83
JohnMcG Avatar answered Oct 12 '22 19:10

JohnMcG