Operator Overloading

Overloading Comparison Operators

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Operator Overloading

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Operator Overloading

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved