Page 164 - DCAP404 _Object Oriented Programming
P. 164
Unit 8: Type Conversion
float y = 20.123; Notes
x=y;
This converts float variable y to an integer before its value assigned to x. The type conversion is
automatic as far as data types involved are built in types. We can also use the assignment
operator in case of objects to copy values of all data members of right hand object to the object
on left hand. The objects in this case are of same data type.
!
Caution But of objects are of different data types we must apply conversion rules for
assignment.
There are three types of situations that arise where data conversion are between incompatible
types.
1. Conversion from built in type to class type.
2. Conversion from class type to built in type.
3. Conversion from one class type to another.
Self Assessment
Fill in the blanks:
1. Implicit type conversion is done automatically by the …………………… whenever data
from different types is intermixed.
2. The type of data to the right of an assignment operator is automatically converted to the
data type of variable on the …………………....
3. An implicit conversion is performed automatically by the compiler when an expression
needs to be ……………………….. into one of its compatible types.
4. The desired data type is simply placed in ……………………….. to the left of the expression
that needs to be converted.
5. That cast is therefore more likely to execute subtle conversion ……………………. if used
incorrectly.
6. If a user-defined conversion can give rise to exceptions or loss of information, then that
conversion should be defined as an …………………….. conversion.
8.2 Basic Type to Class Type
A constructor was used to build a matrix object from an int type array. Similarly, we used
another constructor to build a string type object from a char* type variable. In these examples
constructors performed a defect type conversion from the argument’s type to the constructor’s
class type
Consider the following constructor:
string::string(char*a)
{
length = strlen(a);
name=new char[len+1];
LOVELY PROFESSIONAL UNIVERSITY 157