Is this a proper way to implement an equality check? In Equals
method, I am relying on bad_cast
exception to know if the objects are of the same class or not.
Is there any other way to implement Equals()
in C++?
class Shape
{
public:
virtual ~Shape() = 0;
bool operator==(const Shape& s)
{
return Equals(s);
}
virtual bool Equals(const Shape& s) = 0;
};
class Circle : public Shape
{
bool Equals(const Shape& c) override
{
try
{
const Circle& other = dynamic_cast<const Circle&>(c);
// condition to check equality.
}
catch(std::bad_cast&)
{
return false;
}
catch(...)
{
throw;
}
}
};
class Square : public Shape
{
bool Equals(const Shape& s) override
{
try
{
const Square& other = dynamic_cast<const Square&>(s);
// condition to check equality.
}
catch(std::bad_cast&)
{
return false;
}
catch(...)
{
throw;
}
}
};
typedef std::shared_ptr<Shape> ShapePtr;
typedef std::vector<ShapePtr> Shapes;
Shapes LoadShapes()
{
Shapes shapes;
shapes.push_back(std::make_shared<Circle>(42));
shapes.push_back(std::make_shared<Circle>(52));
shapes.push_back(std::make_shared<Circle>(62));
shapes.push_back(std::make_shared<Square>(10));
return shapes;
}
int main()
{
auto circle = std::make_shared<Circle>(42);
auto shapes = LoadShapes();
for ( auto& shape : shapes)
{
if ( *shape == *circle)
{
std::cout << *shape << "\n";
}
}
}
EDIT
Made the operator==
as non-virtual method.