Browse DevX
Sign up for e-mail newsletters from DevX


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.

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.

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