what does operator int () in c++ class signifies. I came across a class shown below:
whats the purpose of defining operator int and operator float. As far as i remember C++ prohibits overloading c++ keywords. then how does the above program c\ompiles and works?
operator int ();
operator double ();
Foo::Foo (int member)
: member_ (member)
return 1.0 * member_;
Operators are different from keywords, those are conversion operators used to return an equivalent object of one type from another. Kind of like typecasting.
I guess aside from typecasting, all other keywords cannot be overloaded. Since int or double are types, they can be used in conversion operators. Like new and delete for memory.
An Foo::operator X() (where X is a type) is a conversion operator from Foo to X. There is no constraint that the type be a basic type (int, float, etc). It is also possible to provide conversions to class types by the same means.
// declaration of Foo from above
int y = x; // will invoke Foo::operator int(), so y will get a value of 42
float z = x; // will invoke Foo::operator float() so y will get a single-precision value of 42.0
y = (int)x; // explicitly invokes Foo::operator int()