Search code examples
c++dynamicshared-ptr

C++ == operator for child of abstract base class using shared_ptr


I got an abstract base class "Parent" with a pure virtual method and a child class "Child" implementing this method and a member "value". I instantiate objects of the child class as shared_ptr as a means of dynamic binding. I use shared_ptr's here instead of references because I store these objects in a std::vector.

Now I want to compare the two objects "someObject" and "anotherObject" as defined on the bottom of my source code. Therefore, I've overwritten the ==operator in the corresponding Child class. Nevertheless, only the == operator of the shared_ptr gets called. Can I do a comparison of the dynamically binded objects behind at all?

/*
* Parent.h
*/
class Parent{
public:
    virtual ~Parent(){};
    virtual void someFunction() = 0;
};


/*
* Child.h
*/
class Child : public Base{
private:
    short value;

public:
    Child(short value);
    virtual ~Child();
    bool operator==(const Child &other) const;
    void someFunction();
};


/*
* Child.cpp
*/
#include "Child.h"

Child::Child(short value):value(value){}
Child::~Child() {}
void Child::someFunction(){...}

bool Child::operator==(const Child &other) const {
  if(this->value==other.value){
      return true;
  }
  return false;
}


/*
* Some Method
*/
std::shared_ptr<Parent> someObject(new Child(3));
std::shared_ptr<Parent> anotherObject(new Child(4));
//!!!calls == operator for shared_ptr, but not for Child
if(someObject==anotherObject){
//do sth
}

I appreciate any input here! Thank you.

Best,


Solution

  • As Alf suggested you need to change the if statement to compare the objects themselves and not the pointers.

    Additionally if there are subtypes that need special processing to determine if they are equal, your operator== needs to defer to a virtual function to do the actual comparison.

    bool Parent::operator==(const Parent& other) const
    {
        return equals(other);
    }
    
    bool Child::equals(const Parent& other) const
    {
        Child * otherChild = dynamic_cast<Child*>(&other);
        if (otherChild != NULL)
            // compare child to child
        else
            // compare child to other type
    }