Start learning free

LESSON 607 OF 634 · OBJECT-ORIENTED PROGRAMMING

Comparing Objects in C++ in C++

Lesson

TL ; DR:

C++ can't compare two objects of your class until you say how. Define operator== to compare the values. A set also needs operator<, to keep its items in order.


bool operator==(const Time& other) const {
    return hour == other.hour && minute == other.minute;
}

bool operator<(const Time& other) const {
    if (hour != other.hour) {
        return hour < other.hour;
    }

    return minute < other.minute;
}


Full lesson:

Write a == b for two Time objects, and the code doesn't compile. C++ has no default == for a class. It won't guess which fields matter.

Equal by value

A class defines == with a method named operator==. It takes the other object and returns true when the fields match.

const Time& other reads the other object without copying it. The const at the end promises not to change this object.

Sets need an order

A set keeps its items sorted. To place a new item, it asks operator< which one comes first. When neither comes first, the two are the same item. The set keeps just one.

So operator< must use the same fields as operator==. Compare the hours first. When they are equal, compare the minutes.

No free !=

Defining == doesn't give you != in C++17. Write !(a == c) instead, as the code below does.


Your task

The Time class keeps an hour and a minute. Give it operator== and operator<. Two times are equal when the hour and the minute both match.

mainFunction compares three times. Then it inserts them into a set of alarms.

Expected output:

a and b are the same time
a and c are different times
alarms: 2
STEP 1 OF 2
    Ctrl + Enter to check

    Comparing Objects in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free