Ad Hoc Polymorphism  «Prev 

Conversion example C++

Consider the following class, whose purpose is to print nonvisible characters with their ASCII designation; for example, the code 07 (octal) is alarm or bel.

//ASCII printable characters
class pr_char {
 pr_char(int i = 0) : c(i % 128) {}
  void  print() const { cout << rep[c]; }
  int c;
	static char*  rep[128];

char*  pr_char::rep[128] = 
{ "nul", "soh", "stx", "w", "x", "y", "z",""{", "|", "}", "~", "del" };
int main(){
 int      i;
 pr_char  c;
 for (i = 0; i < 128; ++i) {
 c = i;  //or: c = static_cast<pr_char>(i);
 cout << endl;

The constructor creates an automatic conversion from integers to pr_char. Notice, the c = i; statement in the loop implies this conversion. It is also possible to explicitly use a cast.
Unneeded conversions produced by conversion constructors are a source of obscure runtime bugs. Avoid this problem by using the keyword explicit to preface a single-argument constructor. This disables automatic conversion.