Data Conversion
Conversion between Basic Types:
See standard conversions in chapter 2 for this.
Conversion between objects and Basic Types:
a) Conversion From Basic to User defined data type:
A constructor can be used to covert basic data type to user defined data type. It may be important to know that an object can be initialized using one argument constructor as
Square s(10); ß---à Square s=10; // Assume that Square is class name and it has one constructor Square(int).
An example:
const float MTF=3.280833;
class distance
{
int feet;
float inches;
public:
distance() //constructor
{ feet=0; inches=0.0; }
distance(float meters) //constructor with one argument
{ float floatfeet= MTF * meters;
feet=int(floatfeet);
inches=12*(floatfeet-feet); }
void showdist() //display distances
{ cout<<feet<<"\' - "<<inches<<'\"'; }
};
void main()
{
distance dist1=1.144,dist2; // uses 1 argument constructor to
//convert meter to distance
//same as dist1(1.144)
dist2=3.5; // uses 1 argument constructor i.e. same as dist2(3.5).
clrscr();
cout<<"\nDist1 = ";
dist1.showdist();
cout<<"\nDist2 = ";
dist2.showdist();
getch();
}
b) Conversion From User defined to Basic data type:
C++ allows us to define an overloaded casting operator that could be used to covert a class type data to a basic type. Syntax for an overloaded casting operator function is:
operator type_name()
{……….. }
This function converts a class type (of which it is member) data to type_name. The casting operator function should satisfy following conditions.
Ø It must be a class member
Ø It must not specify a return type
Ø It must not have any arguments
An example:
const float MTF=3.280833; //meter to feet
class distance
{
int feet;
float inches;
public:
distance() //constructor
{ feet=0; inches=0.0; }
distance(int ft, float in) //constructor with two arguments
{ feet=ft;
inches=in; }
operator float() //operator function
{ float fracfeet=inches/12;
fracfeet+=float(feet);
return (fracfeet/MTF);
}
};
void main()
{
distance dist1(3,3.37), dist2(5,5.6);
float mtrs=float(dist1); /*Uses conversion function to convert
distance to meter & equivalent to dist1.operator float()*/
cout<<"\nDist1 = "<<mtrs<<" meters";
mtrs=dist2; // dist2.operator float();
cout<<"\nDist2="<<mtrs<<"meters";
}