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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS