Você está na página 1de 15

Type Conversions

 int m;
float x=3.1415;
m=x;
converting one form of data into another form
Automatic Type Conversion
 Automatic type conversion by the C++ compiler from
the type that doesn’t fit, to the type it wants

 4 types of situation might arise in the data conversion:


 conversion from basic type to basic type
 Conversion from basic type to class type
 Conversion from class type to basic type
 Conversion from class type to class type
Types of convertions
 Basic to class type
 Class to basic type
 Class to class type
basic type to basic type
int x;
float y=10.00;
x=y;
basic type to class type
Class time using construtors
{
int hrs;
public:
time(int t)
{
hrs=t/60;
}
};
void main()
{
time t1(85); output : 1hrs
}
class type to basic type
 My constructor function does not support this
operation
 So C++ allow us to define an overloaded casting
operator that could be used to convert a class type data
to basic type.
 It is also known as conversion function
 The casting operator function should satisfy following
conditions
 It must be a class member
 It must not specify return type
 It must not have any arguments
Class to Basic Type
 Casting opeator is used.
operator float ()
{
return (item* price);
}
Main()
{
float a;
a= object;
}
 Syntax:- EXAMPLE
operator typenane() operator double()
{ {
…………//function ……..
statements }
} operator int()
{
………..
}
vector :: operator double()
{
double sum=0;
sum =sum + v;
return (sum);
}
void main()
{
vector v1;
double len=double(v1); OR double len=v1;
}
class Student
{
private:
int rolln0; void main()
float fees;
{
int j;
public:
float f;
Student (int a, float m)
Student st(5,4200.50);
{
rollno = a; j = st; //operator int() is executed
fees = m;
} f = st; //operator float() is executed
operator int()
{ cout<<"\nvalue of j: "<<j<<"\n";
return(rollno); cout<<"\nvalue of f: "<<f<<"\n";
}
operator float() getch();
{
return(fees); }
}
};
class type to class type
 obX=obY;
 Class Y is source class and Class X is destination class

 In case of conversion between objects casting operator


function is applied to destination class.
OR
 And constructor conversion is applied to source file
class minutes //source class
{
int m; class hours //destination class
public: {
minutes(int ms) int h;
{ hours()
m = ms; {
} h =0;
/* operator hours() }
{ public:
hours h1; void show()
{
h1.h = m/60;
cout<<"Hours = "<<h<<"\n";
return(h1);
}
}*/
hours(minutes mm)
void show()
{
{ h=mm.getdata()/60;
cout<<"Minutes = "<<m<<"\n"; }
} };
int getdata()
{
return m;
}
};
int main()
{
minutes min(60);
hours hr;
hr = min; //class minutes to class hours
min.show();
hr.show();
getch();
}
summary
Conversion required Conversion take place in
Source class Destination class
Basic->class NA constructor
Class->basic Casting operator NA
Class->class Casting operator constructor

Você também pode gostar