Why can't I use the cast operator in comparisions?

108 views Asked by At

Assume the following code:

#include <string>
#include <iostream>
using namespace std;
struct A
{
    operator int()
    {
        return 123;
    }
    operator string()
    {
        return string("abc");
    }
};
void main()
{
    A a;
    cout<<(a==123)<<endl;
    //cout<<(a==string("abc"))<<endl;
}

First, I compare object a with an int variable. Then, I attempt to compare it with a string variable, but the program files to compile. With the line containing the comparison commented out, it compiles just fine. What is the problem?

1

There are 1 answers

3
Alok Save On BEST ANSWER

You provided the conversion operators for your class to int as well as std::string,
That ensures the conversion happens appropriately.
However, for the == to work the types being compared must have an == defined.
The language provides an implicit == for int type but == operator overload for std::string and hence the error.