Overloading Comparison Operators

How can I overload comparison operators like == and < for my custom type?

To overload comparison operators like ==, !=, <, >, <=, and >= for your custom type, you can define them as either member functions or non-member functions.

Here's an example of overloading the == and < operators for a custom Player class:

#include <iostream>
#include <string>

class Player {
private:
  std::string name;
  int score;

public:
  Player(const std::string& n, int s)
    : name(n), score(s) {}

  bool operator==(const Player& other) const {
    return score == other.score;
  }

  bool operator<(const Player& other) const {
    return score < other.score;
  }
};

int main() {
  Player p1("Alice", 100);
  Player p2("Bob", 200);

  std::cout << (p1 == p2) << "\n";
  std::cout << (p1 < p2) << "\n";
}
0
1

In this example, we define the == and < operators as member functions of the Player class. The == operator compares the scores of two Player objects for equality, while the < operator compares their scores for less than.

By overloading these operators, we can use them with Player objects just like we would with built-in types. This allows us to write more intuitive and readable code when comparing Player objects.

Note that if you overload the == operator, it's generally a good practice to also overload the != operator. Similarly, if you overload <, consider overloading >, <=, and >= for completeness.

You can also overload these operators as non-member functions, in which case they would take two Player objects as parameters.

Operator Overloading

Discover operator overloading, allowing us to define custom behavior for operators when used with our custom types

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Overloading the Subscript Operator
How can I overload the subscript operator [] for my custom type?
Overloading the Function Call Operator
What is the purpose of overloading the function call operator ()?
Overloading Arithmetic Assignment Operators
How can I overload arithmetic assignment operators like += and *= for my custom type?
Overloading the Stream Insertion Operator
How can I overload the << operator to print objects of my custom type?
Overloading Operators for Type Conversions
Can I overload operators to perform type conversions for my custom type?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant