class binaryOperators
{
public:
int i;
binaryOperators (int tempI = 0)
{
i = tempI;
}
binaryOperators operator+ (const binaryOperators &right);
};
binaryOperators binaryOperators :: operator+ (const binaryOperators &right)
{
return binaryOperators (*this + right.i);
}
binaryOperators operator+ (const binaryOperators &left, const binaryOperators &right)
{
return binaryOperators (left.i + right.i);
}
int main ()
{
binaryOperators obj (10);
obj = 11 + obj;
obj = obj + 11;
return 0;
}
So, here the statement obj = 11 + obj; calls the function with explicit argument specification.
and this one obj = obj + 11; calls the function which is the member of the class. Fine.
The problem is that second call results in an infinite loop.
What are the reasons and how to avoid that?
The conversion from
binaryOperators::i(of typeint) tobinaryOperatorsis implicit (i.e. not declaredexplicit).In the line (1) two
operator+functions can be considered: The member version (2) and the free version (3). Since the LHS is of typebinaryOperators&, the member version is applicable and preferred. Its argument is of typeconst binaryOperators &, and the argument given in line (1) is of typeint, so the compiler tries to convertinttoconst binaryOperators &.Since there is a non-
explicitconstructor with one argument, it is used as an implicit conversion frominttoconst binaryOperators &. Now we have two operands of typesbinaryOperators&andconst binaryOperators &, theoperator+in (2) can be called, and we are right where we started.Lesson: Don’t over-do implicit conversions.