What is the “operator int” function below? What does it do?
class INT
{
int a;
public:
INT(int ix = 0)
{
a = ix;
}
/* Starting here: */
operator int()
{
return a;
}
/* End */
INT operator ++(int)
{
return a++;
}
};
The bolded code is a conversion operator. (AKA cast operator)
It gives you a way to convert from your custom
INTtype to another type (in this case,int) without having to call a special conversion function explicitly.For example, with the convert operator, this code will compile:
Without the convert operator, the above code won’t compile, and you would have to do something else to go from an
INTto anint, such as: