advertisement
Login | Register   
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   TIP BANK
Browse DevX
std::string has been around for 10 years or so. In retrospect, do you think that the decision not to include a const char * conversion operator was right, considering that many functions in the Standard Library still use char * exclusively? Let us know in the C++ Developer Forum.
Partners & Affiliates
advertisement
advertisement
advertisement
advertisement
Rate this item | 0 users have rated this item.
 

Preserve Code Safety with Conversion Operators

Inadvertent object conversion can seriously jeopardize your code's safety. Luckily, conversion operators allow you to enable or disable conversions as you wish, helping you avoid those that are ill-behaved.  


advertisement
ertain objects must be converted to a low-level representation and vice versa. Programmers using std::string objects, for instance, have to convert them to bare char pointers, as in the following example:

string inf="mydata.txt";
ifstream infile(inf.c_str());//const char* required
Similarly, POSIX programmers need to convert <fstream> objects to file descriptors to use native system calls.


How to automate conversions of objects to their underlying types without compromising code safety?


Use conversion operators and explicit constructors to create objects with a dual-interface while avoiding ill-behaved conversions.

  Next Page: Demonstrating the Problem
Page 1: IntroductionPage 3: Declaring Constructors 'explicit'
Page 2: Demonstrating the Problem 
Please rate this item (5=best)
 1  2  3  4  5
advertisement