Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 715
Amir Arad Avatar asked Feb 24 '10 10:02

Amir Arad


People also ask

Can you cast something to const?

2) const_cast can be used to pass const data to a function that doesn't receive const. For example, in the following program fun() receives a normal pointer, but a pointer to a const can be passed with the help of const_cast. 3) It is undefined behavior to modify a value which is initially declared as const.

Why is const correctness important?

The benefit of const correctness is that it prevents you from inadvertently modifying something you didn't expect would be modified.


1 Answers

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
like image 189
AshleysBrain Avatar answered Oct 12 '22 05:10

AshleysBrain