CodeBlanks Logo Icon CodeBlanks

Comparison operators

Learn to overload == and < operators.

Comparison operators

Comparison operators ==, !=, <, <=, >, >= can be overloaded. They return bool.

Example: bool operator==(const Score& other) const { return value == other.value; }. This lets you compare two Score objects with ==. The expression a == b returns true or false. Comparison operators are usually written as const because they do not modify the object. For sorting, defining operator< is enough; std::sort uses it.

operator< and sorting

operator< tells whether one object is less than another. std::sort and other STL algorithms use this operator.

Example: bool operator<(const Score& other) const { return value < other.value; }. This lets you sort Score objects by value. When you sort a std::vector<Score> with std::sort(v.begin(), v.end()), the compiler uses operator<. If operator< is not defined, sorting gives a compile error. That is why defining operator< is important for sortable classes.

Practice Add operator== to the Score class

Add operator== to the Score class in the starting code: its body is return value == other.value;. In main compare a == b; print "Equal" if equal, "Different" otherwise.

Starter code

main.cpp
#include <iostream>

class Score {
public:
    int value;
    Score(int v) : value(v) {}
    // Add the equality operator
};

int main() {
    Score a(10);
    Score b(10);
    // Compare a == b and print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>

class Score {
public:
    int value;
    Score(int v) : value(v) {}
    bool operator==(const Score& other) const {
        return value == other.value;
    }
};

int main() {
    Score a(10);
    Score b(10);
    if (a == b) {
        std::cout << "Equal";
    } else {
        std::cout << "Different";
    }
    return 0;
}

Expected output

Equal

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What type do comparison operators return?

main.cpp
bool operator==(const Score& other) const;
  • int
  • Score
  • bool Correct answer
  • void

Explanation: Comparison operators return bool.

2 Equality operator name

Question
bool ____(const Score& other) const { return value == other.value; }
Answer
bool operator==(const Score& other) const { return value == other.value; }

Explanation: operator== performs equality comparison.

3 Match each operator to its purpose

Term Meaning
operator== Equality
operator< Less than
operator!= Not equal
operator>= Greater or equal

All lessons in Intermediate