return type of Casting operators

pushpat's Avatar, Join Date: Feb 2012
Go4Expert Member
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;
}
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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().
pushpat's Avatar, Join Date: Feb 2012
Go4Expert Member
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);
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
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.
pushpat's Avatar, Join Date: Feb 2012
Go4Expert Member
Thank you xpi0t0s