1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

return type of Casting operators

Discussion in 'C++' started by pushpat, Apr 19, 2012.

  1. pushpat

    pushpat New Member

    Joined:
    Feb 14, 2012
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    :drum: hi folks :)

    Please explain me why C++ done have return type for casting operator? I have googled, understood that its special case and some points, still I am not clear about why compiler dont give error since casting operators not follow general function syntax and does casting operator different from operator overload?

    Thanks in advance
    Code:
    
    #include<iostream>
    using namespace std;
    
    class paise
    {
            float p ;
    	public:
    	paise(int x =0):p(x){}
    	~paise(){}
    	operator int()
    	{
    		cout<<"convertint"<<endl;
    		return p;
    	}
    };
    
    
    void print(int x)
    {
    	cout<<"paise="<<x<<endl;
    }
    
    int main()
    {
    	paise a(4.78);
    	print(a);
    	return 0;
    }
    
    
    
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    I don't understand your question. What output did you get from the above code, and what output did you expect? I would expect:
    convertint
    paise=4

    because 4.78 is passed into a function that takes an int, so the function receives the value 4, which is then assigned to the float p, which is displayed in print().
     
  3. pushpat

    pushpat New Member

    Joined:
    Feb 14, 2012
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    I am extremely sorry , i used 'done' instead of "dont" ...

    I want to know why overloading the typecast operator doesnot have 'return type' .
    i.e operator int(){} doesnt need return type , usually function prototype is
    'return-type function_name(arg);
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,012
    Likes Received:
    203
    Trophy Points:
    0
    Occupation:
    Senior Support Engineer
    Location:
    England
    operator int() casts to int, the return type is already known so it doesn't need specifying again. The syntax if it was specified would be int operator int(), and anything else such as float operator int() would be invalid.
     
  5. pushpat

    pushpat New Member

    Joined:
    Feb 14, 2012
    Messages:
    14
    Likes Received:
    0
    Trophy Points:
    0
    Thank you xpi0t0s :)
     

Share This Page