Wednesday 18 January 2017

Type Conversion

Share & Comment
We know that when constant and variables of different types are mixed in an expression, C applies automatic type conversion to the operands as per certain rules. Similarly, an assignment operation also causes the automatic type conversion. The type of data to the right of assignment operator is automatically converted to the type of variable on the left. For example, the statement

Int m;
Flo
at x = 3.14159;
m = x;

Convert x to an integer before its value is assigned to m. Thus, the fractional part is truncated. The types of conversions are automatic as long as the data types involved are built-in types.

What happens when they are user-defined data types?

Consider the following statement that adds two objects and then assigns the result to a third object.
V3 = v1+v2;      // v1, v2 and v3 are class type objects

When the objects are of the same class type, the operation of addition and assignment are carried out smoothly and the compiler does not make any complaints. We have seen, in the case of class objects, that the values of all the data members of the right-hand object are simply copied into the corresponding members of the object on the left-hand. What if one of the operands is an object and the other is built-in type variable? Or, What if they belong to two different classes?

Since the user-defined data types are designed by us to suit our requirements, the compiler does not support automatic type conversion for such data type. We must, therefore, design the conversion routines by ourselves, if such operation is required.

Three types of situation might arise in the data conversion between incompatible types:

  • Conversion from basic type to class type.
  • Conversion from class type to basic class.
  • Conversion from one class type to another class type.


Tags:

Written by

Hy, i am a Code Geek ! And like to eduate others.

0 comments:

Post a Comment

 
Copyright © C++ Programming | Designed by Templateism.com