tags:

views:

190

answers:

3

I have this here code sample:

class Number 
{ 
  int i;
  public:
    Number(int i1): i(i1) {}
    operator int() const {return i;}
};

What are the implications of removing the const modifier from the casting operator? Does it affect auto casting, and why?

+1  A: 

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.

sharptooth
Did you mean "only be called on *non-const* entities"??
legends2k
@legends2k: Yes, fixed. Thank you.
sharptooth
+9  A: 

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
AshleysBrain
+1 - well earned. Hmmm - I want to cast the value taken from a const object, but I can't, because the conversion (that isn't modifying the source value) isn't const. Stop, look and think and the reasoning is obvious - it's no different to any other method. But I still keep hearing that twilight zone theme. The (at least logical) constness of the source is part of the expected behaviour of the method - what "conversion" means. But then again, consistent rules are, at least, consistent.
Steve314
A: 

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.

Naveen