Ad Hoc Polymorphism  «Prev  Next»
Lesson 4 ADT conversions
Objective Identify the conversion constructor
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.
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