Unconsting a Const Reference or Object

Unconsting a Const Reference or Object

I have encountered a problem as follows:

void foo(const int& var){  foo2(var);}void foo2(int& var)...

So what I did was

void foo(const int& var){  foo2((int&)var);       ^^^^^^}

and it compiled *_* and worked fine.

However, is it OK to cast away const & to & and pass in? What is actually happening when I cast the variable?if the var is an object, is the constructor called?

Removing an object’s const qualifier is usually an indication of a design flaw and should be avoided in general. In your example, changing the declaration of foo2() from:

void foo2(int& var)


void foo2(const int& var)

would solve this problem without having to resort to brute-force typecasting.

Nevertheless, there are situations in which you have no other choice but to remove an object’s “constness” explicitly. To perform this operation, it’s advisable to use operator const_cast rather than C-style cast. const_cast can only remove the const/volatile qualifiers of an object. Therefore, it’s safer to use and it makes the programmer’s intent more explicit. For example:

void foo(const int & var)  {   foo2(const_cast  (var) );// remove const  }

It’s always safe to remove the constness of an object as long as the program doesn’t attempt to modify its value; any attempt to change such a variable yields undefined behavior.

The cast operation occurs at compile time; it doesn’t incur any overhead of any kind (i.e., it won’t invoke an object’s constructor behind your back, nor will it create a temporary variable).


Share the Post: