I have this code sample:
class Number
{
int i;
public:
Number(int i1): i(i1) {}
operator int() const {return i;}
};
What are
The const
version can be called regardless of whether the class Number
instance is const or not. If the operator is declared non-const it can only be called on non-const entities - when you try to implicitly use it where it can't be called you'll get a compile error.
If the conversion operator is not const, you can't convert const objects:
const Number n(5);
int x = n; // error: cannot call non-const conversion operator
If you have a function like this:
void f(const Number& n)
{
int n1 = n;
}
It will start giving compilation error if you remove const in the casting operator.