bool operator >(Counter & rhs)
         {

         }

         bool operator ==(Counter & rhs)
         {

         }

         bool operator !=(Counter & rhs)

Dani AI

Generated

As started to explain, those are operator overloads for comparing two Counter objects. The practical rules that students usually miss are about function signatures, consistency, and minimal implementation.

Prefer signatures that take a const reference and are const member functions. Implement operator== by comparing all relevant data members, make operator!= simply the negation of operator==, and implement ordering operators in a consistent way (implement one like < and express > in terms of it). For types with multiple fields, std::tie is a concise, correct way to compare tuples of members. For modern code, consider the C++20 three-way comparison (operator<=>) to get all ordering operators auto-generated.

Example patterns:

bool operator==(const Counter& other) const
{
    return std::tie(count, extra) == std::tie(other.count, other.extra);
}

bool operator!=(const Counter& other) const
{
    return !(*this == other);
}

bool operator<(const Counter& other) const
{
    return std::tie(count, extra) < std::tie(other.count, other.extra);
}

bool operator>(const Counter& other) const
{
    return other < *this;
}

Common pitfalls: using non-const parameters or forgetting the trailing const prevents calls on const objects; writing inconsistent comparisons breaks containers and algorithms that rely on strict weak ordering; making operators members vs free functions affects implicit conversions. For authoritative details and edge cases, see the operator overload documentation on cppreference: Operators (C++).

Recommended Answers

All 2 Replies

Those are overloaded binary operators. Basically you are specifying what myClass1 > myClass2 really means. For example, say you had a class that contains 2 integers, a and b. If you wanted to implement some functionality that compared the two classes (for example a greater than > operator) your computer isn't going to make any assumptions on which values to compare.


Say that you wanted the > operator to compare the member 'a' between counter classes:

bool operator >(Counter & rhs)
{
    return this.a > rhs.a
}

I'm a bit of a C++ noob/washout but this stuff is simple :P Make sure to pay attention to your teacher!

Thank you..badass..right on...simple yet so complex..if ur behind that is...but gracias my friend

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.