dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: Beginner
Feb 14, 2000

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date