There's a rather nondescript book called "Using Borland C++" by Lee
and Mark Atkinson (Que Corporation) which presents a rather good
discussion of typecast operator overloading.
I am presenting below a summary of what I have gathered. I would
appreciate if someone could point out to something that is specific to
Borland C++ and is not supported by the ANSI standard. I am also
concerned that some of the information may be outdated since the book
is quite old (1991 edition).
1). Cast operator functions are declued using the following syntax:
operator typename ();
operator typename* ();
2). The target type of the conversion cannot be an enumeration or a
typedef name.
3). You rannot specify a return type.
4). You cannot declare arguments for a cast operator function. It is
assumed that
the function is dealing with *this as input.
5). Cast operator functions are inherited and they can be virtual
functions
6). Only one cast operator function can be implicitly applied to a
class object
7). Cast operator functions cannot be overloaded
8). A cast operator function in a derived class hides a cast operator
function in its base class only if the target type is exactly the
same.
9). The cast operator functions are used in serializing operations.
// ~~~~~~~ Code snippet begin ~~~~~~~
#include <iostream.h>
//////////////////////////////////////////////////////
class A
{
int dat;
public:
A(int num = 0 ) : dat(num) {}
operator int() {return dat;} // castop to int
};
//////////////////////////////////////////////////////
class X
{
int dat;
public:
X(int num = 0) : dat(num){}
operator int() {return dat;} // castop to int
operator A() // castop to class A
{
A temp = dat;
return temp;
}
};
//////////////////////////////////////////////////////
int main()
{
X stuff = 37;
A more = 0;
int hold;
hold = (int)stuff;
cout << hold << endl;
more = stuff; // convert X::stuff to A::more
hold = (int)more; // convert A::more to int
cout << hold << endl;
}
// ~~~~~~~ Code snippet end ~~~~~~~
Regards,
Nimmi