Page 167 - DCAP404 _Object Oriented Programming
P. 167
Object-oriented Programming
Notes In the string example discussed earlier, we can convert the object string to char* as follows:
string::operator char*()
{
retum(str);
}
Did u know? What is dynamic_cast?
Dynamic_cast can be used only with pointers and references to objects. Its purpose is to
ensure that the result of the type conversion is a valid complete object of the requested
class.
Self Assessment
Fill in the blanks:
11. Conversion functions have no …………………………… , and the return type is implicitly
the conversion type.
12. …………………………. functions can be inherited.
13. C++ allows us to define an overloaded ……………………. operator that convert a class
type data to basic type.
8.4 Class Type to another Class Type
We have just seen data conversion techniques from a basic to class type and a class to basic type.
But sometimes we would like to convert one class data type to another class type.
Example:
Objl = Obj2 ; //Obj1 and Obj2 are objects of different classes.
Obj1 is an object of class one and Obj2 is an object of class two. The class two type data is
converted to class one type data and the converted value is assigned to the Obj1. Since the
conversion takes place from class two to class one, two is known as the source and one is known
as the destination class.
Such conversion between objects of different classes can be carried out by either a constructor or
a conversion function. Which form to use, depends upon where we want the type-conversion
function to be located, whether in the source class or in the destination class.
We studied that the casting operator function
Operator typename()
Converts the class object of which it is a member to typename. The type name may be a built-in
type or a user defined one (another class type). In the case of conversions between objects,
typename refers to the destination class. Therefore, when a class needs to be converted, a casting
operator function can be used. The conversion takes place in the source class and the result is
given to the destination class object.
Let us consider a single-argument constructor function which serves as an instruction for
converting the argument’s type to the class type of which it is a member. The argument belongs
160 LOVELY PROFESSIONAL UNIVERSITY