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


advertisement
 

Use Explicit Conversion Functions to Avert Reckless Implicit Conversions -3 : Page 3

Conversion functions are inherently unsafe as they might surprise you with implicit conversions over which you have no control. This is why such functions have been avoided for years. Learn how the new C++0x explicit conversion functions put an end to years of conversion functions blues.


advertisement

Explicit Conversion Functions
You're already familiar with the use of explicit in constructors that take a single argument. Unless declared explicit, a constructor C(arg) operates as implicit conversion functions that converts arg to C. C++0x extends the use of explicit to conversion functions as well. When you declare a conversion function as explicit, implicit conversions are permitted only in direct initialization expressions:


class BuggyString {
//now explicit
 explicit operator char*();
 explicit operator const char* () const;
};

const char * ps(str);//OK, direct initialization


 
ps=str; //Error, explicit cast required

ps=(const char *) str; //OK, C-style cast 
ps=static_cast<const char*>(str); //OK, new style cast

Safe and Sound
The use of explicitguarantees that conversion functions do not surprise you with undesirable conversions. Instead, every conversion operation requires an explicit permission from you in the form of at cast notation (except in the case of direct initializations). Explicit conversion functions thus offer a safe and uniform method for conversions.





Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap