3.3 Type Casting
3.3 Type Casting
3.3 Type Casting
--Prof. S.N.Shelke
Type Conversion
It is the process of converting one type into another. In other words
memory location
3
Implicit type conversion (cont...)
Implicit type conversion (also called automatic type
conversion or coercion) is performed whenever one fundamental data type
is expected, but a different fundamental data type is supplied, and the user
does not explicitly tell the compiler how to perform this conversion (via a
cast).
double d = 3; // convert integer 3 to a double
short s = 2; // convert integer 2 to a short
short int i = 2;
int s = i; // convert from short to int
cout << s; Output:
float f = 0.1234; 2
0.1234
double d= f;
cout << d;
2. Explicit Type casting
Use explicit type conversion (type casting) to convert an item from one
data type to another
C-style casts
In standard C programming, casts are done via the () operator, with the
name of the type to cast to inside. For example:
int i1 = 10;
int i2 = 4;
float f = (float)i1 / i2;
C++ will also let you use a C-style cast with a more function-call like syntax:
int i1 = 10;
int i2 = 4;
float f = float(i1) / i2;
Type conversion
int x;
float m=4.345;
x=m;
For eg:
Operator typename()
{
……………..
……………. (Function statements)
…………….
}
#include<iostream> sample::operator double()
Using namespace std; {
class sample double sum=0;
{ for(int i=0;i<5;i++)
int v[5]; {
public: sum=sum+v[i];
void read(); }
operator double(); return sum;
}; }
operator typename();
seconds sec1=90;
sec1.display();
min1.display();
minutes min2=5;
min2.display();
sec2.display();
return 0;
}
Prof. S. N. Shelke
(Assistant Professor)
Department of Computer
Engineering
Sinhgad Academy of Engineering,
Kondhwa, Pune