C++: Overloading overloaded operators
Code:
binaryOperators binaryOperators :: operator+ (const binaryOperators &right) The problem is that second call results in an infinite loop. What are the reasons and how to avoid that? |
Why
Code:
binaryOperators binaryOperators :: operator+ (const binaryOperators &right) Code:
binaryOperators binaryOperators :: operator+ (const binaryOperators &right) |
I get your point, but could you explain in detail why the previous call results in an infinite loop?
|
This.i not this? You're recursively calling object + thing's value, not object's value + thing's value?
|
Quote:
In addition, your choice of two versions of operator+ doesn't make sense. The first is a non const member function, so it will cover all the cases where the left operand is a non const binaryOperators object. The second is not a member function but takes const binaryOperators objects for left operand. Why would you want that second function and why would you want the first one to only take non const left operands? The typical reason for a non member version of operator+ is to take a left operand type that is not a object of the class you are working on. |
I think that Anisha ask why compiler not warn about ambiguity between these two functions, when calling
Code:
binaryOperators + i_casted_for_binaryOperators Code:
binaryOperators operator+ (binaryOperators left, const binaryOperators &right) |
Quote:
There is no ambiguity because one definition required a non const left operand and the other takes a const left operand. When the left operand actually is const, the compiler can only use the definition that takes a const left operand. No hint of ambiguity there. When the left operand is non const, a definition that takes a const left operand could be used (some ambiguity there) but the definition that takes a non const left operand is more specific. The ambiguity is resolved when one definition is more specific than the other. Next consider the statement Code:
obj = 11 + obj; When you implicitly cast an integer to a binaryOperators, the result is a temporary object, and a temporary object passed by reference to a function is const. So even if the int had not been const, the binaryOperators object it becomes would be const. The fact that the right operand is non const makes no difference because both operator+ definitions take only const right hand operands (so neither definition is a less specific fit to the right hand operand). Only one definition fits the const left hand operand, so that definition is used. |
All times are GMT -5. The time now is 10:39 PM. |