I am currently trying to understand operator overloading in C++.I tried overloading operator '!=' in the following code:
#include <iostream>
using namespace std;
class MyClass{
int a=0;int b=0;
public:
MyClass() = default;
MyClass(int x,int y){a = x;b=y;}
MyClass(const MyClass& ob){a = ob.a;b = ob.b;}
MyClass& operator=(const MyClass& ob) = default;
bool operator!=(const MyClass& ob){
return a!=ob.a && b!=ob.b;
}
};
int main() {
MyClass ob{112,981};
/* This Works
MyClass ob2{211,121};
if(ob!=ob2){ */
/*This also works
if(ob.operator!=({211,121})){ */
//Why does this does not work ??
if(ob!={211,121}){
cout<<"Operator != overloaded"<<endl;
}
return 0;
}
In the main function, the if(ob!={211,121}){...}
does not work and leads to following compilation error:
prog.cpp: In function ‘int main()’:
prog.cpp:25:9: error: expected primary-expression before ‘{’ token
if(ob!={211,121}){
^
prog.cpp:25:9: error: expected ‘)’ before ‘{’ token
Moreover to my surprise, When I tried the following variation to implement the same logic, it worked:
if(ob.operator!=({211,121})){
return a!=ob.a && b!=ob.b;
}
Can someone please explain the reason?