Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ use operator== instead of operator!= automatically [closed]

Tags:

c++

I understand C++ can't define operator== automatically for a class, but why can't it use !(a == b) for a != b when operator!= isn't available but operator== is?

I'm aware of std::rel_ops although I hadn't heard of it before today.

like image 867
XTF Avatar asked Oct 17 '12 18:10

XTF


People also ask

Can?: operator be overloaded in C++?

You can redefine or overload the function of most built-in operators in C++. These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions.

Which operator can t be overloaded in C++?

Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof , which is technically an operator).

Why operator overloading is used?

Operator overloading facilitates the specification of user-defined implementation for operations wherein one or both operands are of user-defined class or structure type. This helps user-defined types to behave much like the fundamental primitive data types.

Which choice is a valid way to overload the ternary conditional operator?

It's not possible to overload the ternary operator.


1 Answers

Because operator== does not necessarily mean the opposite of operator!=.

I cannot think of any instance where operator== would not mean !operator!=, but they are separate operators. One of the most liberating and, at times, most frustrating things about C++ is that C++ applies a minimal set of restrictions about how you can write your code. If you have an instance where operator== is not the opposite of operator!=, then you should be able to express that in C++. And, in fact, you can.

You take the good with the bad in C++. You may consider this to be in the set of "the bad".

Bear in mind that in the vast majority of cases, it is trivial to correctly implement operator!= in terms of operator==.

bool Gizmo::operator!=(const Gizmo& rhs) const
{
  return !operator==(rhs);
}
like image 155
John Dibling Avatar answered Sep 27 '22 17:09

John Dibling