04. Data Conversion
04. Data Conversion
Oriented
Programming
Using
C ++
Data Conversion/Type Casting
Abdul Wahab
Lecturer
University of Science and Technology Bannu
abdul_bu@yahoo.com
1
Type Casting
Converting one data type into another data type is called ‘Type Casting’
or ‘Data Conversion’
2
1. Conversion from Basic to Basic data type
3
Example:
Implicit Data Conversion Explicit Data Conversion
Ouput Ouput
D B
65
4
2. Conversion from Basic data type to User-defined data type
In this type the left-hand operand of = sign is always class type and right-
hand operand is always basic type.
The program given below explains the conversion from basic to class
type.
5
Example:
class data
{
int x; void main()
float f; {
public : clrscr();
data()
data Z;
{ x=0; f=0; }
Z=1;
data(float m) Z.show();
{
x=2; Z=5.6;
f=m;
Z.show();
}
}
void show()
{
cout<<"\nX= "<<x<<" F="<<f;
}
};
6
Output
7
3. Conversion from Class type to basic data type
8
3. Conversion from Class type to basic data type
The compiler first searches for the operator keyword followed by data
type and if it is not defined, it applies the conversion functions.
In this type, the left-hand operand is always of basic data type and right-
hand operand is always of class type. While carrying this
conversion, the statement should satisfy the following conditions:
– The conversion function should not have any argument.
– Do not mention return type.
– It should be a class member function.
9
Example:
class data void main()
{
{
int x;
float f; clrscr();
int j;
public : float k;
data() data Z;
{ x=0; f=0;}
Z=6.6;
data(float m)
{ x=2; f=m; } j=Z;
k=Z;
operator int() cout<<"\n Value of j: "<<j;
{ return (x); }
cout<<"\n Value of k: "<<k;
operator float() }
{ return (f); }
};
10
Output
11
4. Conversion from one Class type to another Class type
The conversion happens from class ABC to XYZ. The ABC is a source
class and XYZ is a destination class.
12
4. Conversion from one Class type to another Class type
We know the operator function operator data-type(). Here, data type may
be built-in data type or user-defined data type.
13
Example:
class hours
class minutes
{
{
int m; float h;
public : public:
minutes() void operator = (minutes x)
{ { h = x.get() / 60.0; }
m=240;
void show ()
}
{ cout<< "\n Hours = "<<h; }
get() };
{ void main()
return (m); {
}
clrscr();
void show() minutes m;
{ hours h;
cout <<"\n Minutes = "<<m; h = m;
} m.show(); h.show();
};
}
14
Output
15
Have a Good Day!