Explain with an example how one user defined data type can be converted to a predefined data type
A whole new concept is involved in conversion from user defined to basic data type, which is known as the overloading casting operator.
operator type()
{
.
.
.
}
Overloaded casting operator actually overloads the built in casting operator. For example, you can achieve different functionality from a float casting operator. Syntax of overloaded casting operator is simple.
You can see that it is a sort of function with no return type and no arguments. The ‘operator’ is the keyword that has to be used followed by basic data type. For example If you want to overload the float operator. You will overload it like operator float() {}.
There are three conditions that need to be satisfied for an overloaded casting operator.
When you define this overloaded casting operator in a class and when you equate the object of that class with the basic data type, this function will be automatically called on the object. This concept will be explained by example.
include <iostream>
using namespace std;
const float MeterToFloat=3.280833;
// Meter to feet
class Distance {
int feet;
float inches;
public:
Distance() // Default Constructor {
feet=0;
inches=0.0;
}
Distance(int ft, float in) //two arguements constructor {
feet=ft;
inches=in;
}
operator float() //overloaded casting operator {
float feetinfractions=inches/12;
feetinfractions+=float(feet);
return (feetinfractions/MeterToFloat);
}
};
int main() {
int feet;
float inches;
cout <<"Enter distance in Feet and Inches.";
cout<<"\nFeet:";
cin>>feet;
cout<<"Inches:";
cin>>inches;
Distance dist(feet, inches);
float meters=dist;
// This will call overloaded casting operator
cout<<"Converted Distance in Meters is: "<< meters;
}
Comments
Leave a comment