Amir Arad
Amir Arad

Reputation: 6754

casting operator - const vs non-const

I have this 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?

Upvotes: 17

Views: 5051

Answers (3)

AshleysBrain
AshleysBrain

Reputation: 22641

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

Upvotes: 30

sharptooth
sharptooth

Reputation: 170569

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.

Upvotes: 6

Naveen
Naveen

Reputation: 73503

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.

Upvotes: 6

Related Questions