Page 166 - DCAP404 _Object Oriented Programming
P. 166
Unit 8: Type Conversion
Notes
Notes Note that the constructors used for the type conversion take a single argument
whose type is to be converted.
In both the examples, the left-hand operand of = operator is always a class object. Hence, we can
also accomplish this conversion using an overloaded = operator.
Self Assessment
Fill in the blanks:
7. You can define a member function of a class, called a conversion function that converts
from the type of its class to another…………………….. .
8. Classes, enumerations , ……………………….. , function types, or array types cannot be
declared or defined in the conversion_type.
9. The conversion operator can be defined either inside the ……………………. type.
10. Where the operator is the required keyword and type is the required…………………. .
8.3 Class Type to Basic Type
The constructor functions do not support conversion from a class to basic type. C++ allows us to
define a overloaded casting operator that convert a class type data to basic type. The general
form of an overloaded casting operator function, also referred to as a conversion function, is:
operator typename()
{
//Program statement
}
This function converts a class type data to type name. For example, the operator double() converts
a class object to type double, in the following conversion function:
vector:: operator double()
{
double sum = 0;
for(int I = 0; i<size; i++)
sum = sum + v[i] * v[i ]; //scalar magnitude
return sqrt(sum);
}
The casting operator should satisfy the following conditions.
1. It must be a class member.
2. It must not specify a return type.
3. It must not have any arguments. Since it is a member function, it is invoked by the object
and therefore, the values used for, Conversion inside the function belongs to the object
that invoked the function. As a result function does not need an argument.
LOVELY PROFESSIONAL UNIVERSITY 159