Ad Hoc Polymorphism  «Prev  Next»
Lesson 4 ADT conversions
Objective Identify the conversion constructor

Abstract Data Type Conversions using C++

Given a class declaration and a function to test the class, identify the conversion constructor and explain what will go wrong when running the test function.
One aim of object-oriented programming using C++ is the integration of user-defined ADTs and built-in types. To achieve this, there is a mechanism for having a member function provide an explicit conversion. Explicit type conversion of an expression is necessary when either the implicit conversions are not desired or the expression will not otherwise be legal. In Building Classes in C++, the previous course in this series, we saw how a constructor of one argument is by de facto a type conversion from the argument's type to the constructor's class type.

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.
For example, we can convert from an already-defined type to a user-defined type:
my_string::my_string(const char* p);

This is automatically a type conversion from char* to my_string. It is available both explicitly and implicitly. Explicitly, it is used as a conversion operation in either cast or functional form. Thus, both of the following pieces of code work:

my_string s;
char*  logo = "Geometrics Inc";

s = static_cast<my_string>(logo);

s = logo;  //implicit invocation of conversion

Conversion Constructor - Exercise

Click the exercise link below to identify a class's conversion constructor and explain what will go wrong when running a function to test the given class declaration.
Conversion Constructor - Exercise