Ad Hoc Polymorphism  «Prev  Next»
Lesson 5 ADT conversions
Objective Conversion functions in C++

ADT conversions (C++ member functions)

Understand how to create special conversion member functions to convert from a user-defined type to built-in type.
While it is relatively easy to use a constructor to convert from an already-defined type to a user-defined type, it is not possible to add a constructor to a built-in type such as int or double. However, we can define a special conversion function inside the class to achieve the same thing. To do this, we use the keyword operator.
The general form of such a special conversion member function is:
operator type() { ..... }

Using our my_string example, if we want a conversion from my_string to char*, we would define the following special conversion function inside the my_string class:

my_string::operator char*(){
 char* p = new char[len + 1];
 strcpy(s, p);
 return p;
Such a member function must be nonstatic. It cannot have parameters and does not have a declared return type. It must return an expression of the designated type. Notice that we did not simply return the value of the private member s. To do this would violate the integrity of my_string objects.