devxlogo

Unconsting a Const Reference or Object

Unconsting a Const Reference or Object

Question:
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?

Answer:
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)

to:

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).

See also  5 Benefits of Using Time Tracking Software
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist