Cpp - Overload equality operator ==

Introduction

We can overload the equality operator == to support custom comparison.

Demo

#include <iostream>
  
class Cart/* w  w  w. j  a  v  a  2  s .co m*/
{
public:
    Cart();
    // copy constructor and destructor use default
    int getSpeed() const { return *speed; }
    void setSpeed(int newSpeed) { *speed = newSpeed; }
    bool operator==(const Cart&);
  
private:
    int *speed;
};
  
Cart::Cart()
{
    speed = new int;
    *speed = 5;
}
  
bool Cart::operator==(const Cart& rhs)
{
    if (this == &rhs)
    {
        return true;
    }
    if (this->getSpeed() >= rhs.getSpeed())
    {
        return true;
    }
    return false;
}
  
int main()
{
    Cart my_cart;
    std::cout << "speed: " << my_cart.getSpeed() << "\n";
    std::cout << "Setting speed to 8 ...\n";
    my_cart.setSpeed(8);
    Cart your_cart;
    std::cout << "speed: " << your_cart.getSpeed() << "\n";
    std::cout << "Setting speed to 7 ...\n";
    your_cart.setSpeed(7);
    if (my_cart == your_cart)
    {
        std::cout << "equals\n";
    }
    else
    {
        std::cout << "not equals\n";
    }
    return 0;
}

Result