TYPE CONVERSIONS
IN C++
By
Prof.Manikandan
QMC College, Medavakkam.
TYPE CONVERSIONS
The compiler
does not support automatic type
conversions for the user defined data types.
We can use casting operators functions to do this.
Data type varname = Static_cast <data type>
Syn:
int main()
{
int a; int b;
Float y=Static_cast <float> (a)/b;
..
}
Static_cast operator is used to convert a given
expression to the specified type.
Example:
int a=31;
int b=3;
float y=staitc_cast <float>(a)/b;
Out put:
10.3333
EXAMPLE PROGRAM
#include<iostream.h>
int main()
{
int a=31;
int b=3;
float x=a/b;
float y=static_cast<float> (a)/b;
cout<<"output without static_cast ="<<x;
cout<<"output with static_cast ="<<y;
return 0;
}
Output:
output without static_cast =10
output with static_cast =10.3333
1.
2.
3.
Using the static_cast to an integer as float
returns a float value.
The casting operator function should satisfy the
following conditions.
It must be a class member.
It must not specify a return value.
It must not have any arguments.