I wonder if operator!= is automatically provided when operator== is defined within my class? When I have operator== defined in class A, obviously A a, A b, a == b works, but a != b doesn't. However I am not sure if it always happens. Are there any exceptions from this?
7 Answers
No, operators (apart from assignment) are never automatically generated. It's easy enough to define it in terms of ==:
bool operator!=(A const & l, A const & r) {return !(l == r);}
1 Comment
This is true since C++20. Earlier C++ standard versions do not provide operator!= from operator== automatically.
4 Comments
<=> operator then all the other 6 operators are defined in one swoop.operator< and operator>.operator== and operator<=>, if a simple equality check can be done more efficiently than determining the ordering between two values. E.g., == for a string can short circuit and return false if the lengths differ, while <=> always has to at least dereference and compare first character, and potentially has to scan the whole of the shorter string if it is a prefix of the other.The operator != is not automatically provided for you. You may want to read about rel_ops namespace if you want such automation. Essentially you can say
using namespace std::rel_ops;
before using operator !=.
1 Comment
What you're after isn't provided by the language for obvious reasons. What you want is provided for by boost::operators:
class MyClass : boost::operators<MyClass> {
bool operator==(const MyInt& x) const;
}
will get you an operator!=() based on your operator==()
Comments
Nope. You have to define it explicitly.
Code:
#include <iostream>
using namespace std;
class a
{
private:
int b;
public:
a(int B): b(B)
bool operator == (const a & other) { return this->b == other.b; }
};
int main()
{
a a1(10);
a a2(15);
if (a1 != a2)
{
cout << "Not equal" << endl;
}
}
Output:
[ djhaskin987@des-arch-danhas:~ ]$ g++ a.cpp
a.cpp: In constructor ‘a::a(int)’:
a.cpp:11:9: error: expected ‘{’ before ‘bool’
bool operator == (const a & other) { return this->b == other.b; }
^
a.cpp: In function ‘int main()’:
a.cpp:18:12: error: no match for ‘operator!=’ (operand types are ‘a’ and ‘a’)
if (a1 != a2)
^
a.cpp:18:12: note: candidates are: ...
<to have all of them)