9 - Data Conversion
9 - Data Conversion
Lesson 9
Objectives
Data Conversion
We have seen in many situations that the ‘=’ assignment operator for assigning a basic data type to
other and also an object being assigned to other object. Now we will see the situations where
different data types (user define, basic, object etc) can be converted to each other as well. Starting
the discussion from the topic below we shall proceed to next cases.
Implicit Cast: such kind of cast is take place automatically. This is carried out by calling some
special routines by compiler to convert the given basic data type. Simple rule for the implicit cast
is that if the size of the variable on right side of ‘=’ is less than or equal to that of left hand side.
For example a character can be stored in integer, an integer to double and etc. These conversions
are called implicit because they are not apparent in the program.
Explicit Cast: sometimes we want to force the compiler to convert one type to another. To
do this we use the cast operator. For instance, to convert float to integer, we can say
intvar = static_cast <int> (floatvar); this will provide and explicit conversion. It is obvious that
static_cast <int> () is intended to convert from float to int. However, such conversions use the
same built-in routines as implicit conversions.
#include<iostream>
using namespace std;
///////////////////////////
class Distance
{
private:
const float MTF; //meter to feet
int feet;
float inches;
public:
Distance() : feet(0), inches (0.0), MTF (3.280833F)
AJ/Handout 9 -2- Object-Oriented Programming
{}
Distance (float meters) : MTF(3.280833F)
{
float fltfeet = MTF * meters;
feet = int (fltfeet);
inches = 12 * (fltfeet - feet);
}
Distance (int ft, float in) : feet(ft), inches(in), MTF(3.280833F)
{}
void getdist()
{
cout<<”Enter Feet:”; cin>>feet;
cout<<”Enter Inches:”; cin>>inches;
}
void showdist() const
{cout<<feet<<”\”<<inches;}
Distance dist2(5,10.25);
Here we can see that ultimately meter is converted to feet and inches (Distance type Object) and
assigned to the Object made by this constructor. That is, Distance dist1=2.35;