dcsimg
Login | Register   
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: Intermediate
Mar 3, 2003

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Using the Const_cast Operator


The const_cast operator takes the form:
 
    const_cast<T> (expr)

It is used to add or remove the ``const-ness'' or ``volatile-ness'' from a type. Consider a function, f, which takes a non-const argument:
 
   double f( double& d );

Say you wish to call f from another function g:
 
   void g (const double& d)
   {
     val = f(d);
   }

Because d is const and should not be modified, the compiler will complain because f may potentially modify its value. To get around this dilemma, use a const_cast:
  
  void g (const double& d)
   {
      val = f(const_cast<double&>(d));
   }

This strips away the ``const-ness'' of d before passing it to f. You cannot use const_cast for any other types of casts, such as casting a base class pointer to a derived class pointer. If you do so, the compiler will report an error.
Sridhar Reddy
 
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