Fixing Invalid Operands to Binary Expression Error in C++
The respective issue might occur when a variable or object is taken as a function, or the operator used with the operands is wrong.
Example 1: Most Vexing Parse
This is a simple C++ program written to return a number on the output:
using namespace std;
int main()
{
int A();
cout << "Enter number: ";
cin >> A;
cin.ignore();
cout << "Entered Number"<< A <<"\n";
cin.get();
}
When the above program is compiled, it returns an ambiguous overload for operator error, which means that there is an operator and operand incompatibility. This type of condition is known as the most vexing parse, which demonstrates that the A is being treated as a function here and the function cannot be passed as a parameter to the >> operator.
This error in the above code can be fixed by removing the parentheses that make it a function. When these parentheses are removed, it is not treated as a function rather it is taken as a variable:
using namespace std;
int main()
{
int A;
cout << "Enter a number: ";
cin >> A;
cin.ignore();
cout << "Entered Number is:"<< A <<"\n";
cin.get();
}
Now, when the debugged code is run, the compiler executes the program successfully.
Example 2: External Class Objects with Comparison Operator
This is a simple C++ program to compare two parameters declared in the Plant Class.
using namespace std;
class Dimensions{
public:
int length;
};
int main(){
Dimensions x, y;
x.length = 12;
y.length = 10;
if(x != y){
// do something
}
}
When the above program is executed, it returns the “no match for ‘operator’” error, as this error occurs because the properties of an external class are compared:
An error, caused because of comparing the properties of external class objects, can be fixed by overloading the given operator. This will make the operator aware of the required class:
using namespace std;
class Dimensions{
public:
int length;
};
static bool operator!=(const Tree& obj1, const Tree& obj2) {
return obj1.length != obj2.length;
}
int main(){
Dimensions x, y;
x.length = 12;
y.length = 10;
if(x != y){
cout << "Both dimensions are not the same." << endl;
}
}
The operators are overloaded to make the operator aware of the class already:
Conclusion
Invalid Operands to Binary Expression Error in C++ occurs due to either the most Vexing Parse or comparison of properties of the objects of the external class. These errors can be fixed by removing parentheses with the variable, which would make it function, and by overloading the operators.