0

when a operator function is implemented as a member function left most operand must be object of operator's class but in code below

#include<iostream>
    using namespace std;
    class ffloat {
      private:
        float a;
      public:
        ffloat():a(34.566){}
        operator int () {
          return a=static_cast<int >(a);
        }
     };

     int main() {
       ffloat w;
       int x;
       x=w;
       cout<<x<<endl;
     }

left most operand is variable,then why compiler didn't send a error Thanks in advance....

6
  • 1
    return a=static_cast<int >(a); Do you understand what this does? If you made your operator a const function, the compiler would prevent this probable mistake. Commented Mar 2, 2015 at 3:43
  • is something wrong with that... Commented Mar 2, 2015 at 3:45
  • I don't know. That's why I'm asking if you understand what it does. It will change the value of a in the object. Commented Mar 2, 2015 at 3:46
  • yess... But i wrote code keeping operator overloading in mind....@neil krirk Commented Mar 2, 2015 at 3:51
  • @virusai the normal semantics of conversion operator is that it returns a converted value but without making any change to the object. For example ffloat w; cout << static_cast<int>(w); cout << "," << w << endl; ought to display 34 34.566 but in your code it will display 34 34. Commented Mar 2, 2015 at 4:31

2 Answers 2

2

operator int() is a conversion function and its only operand is the implicit 'this' argument. Therefore x=w is not violating the rule since x is not an operand to the conversion. This is in part why it is fine to write int(w) there is no missing operand here. The rule you are referring to is about operators like '+ - * /' which can have 2 operands.

Sign up to request clarification or add additional context in comments.

1 Comment

Then conversion operator behaves as unary operator ' correct me if am wrong '
0

Actually, a=static_cast<int >(a) means that a should be casted as integer from float a and then it returns that as an integer.

Everything is valid, your operator int should return int

9 Comments

I don't understand your explanation.
let a to be the integer version of former value of a (it will be rounded) and then return this as the return value as well
This operator int will modify the state of the object. This is not how conversion operations usually work.
Well, it's not forbidden to alter the state (it's not a "const" :) )
That's not what am asking what am i asking is according to rule " when a operator function is implemented as a member function left most operand must be object of operator's class "but in code above object is not left most operand....
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.