Answer to Question #179345 in C++ for Aditya

Question #179345

Explain with an example how one user defined data type can be converted to a predefined data type


1
Expert's answer
2021-04-08T03:37:46-0400

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.

  1. Overloaded casting operator does not have any return type.
  2. It cannot take any parameters or in other words no arguments can be passed to an overloaded casting operator.
  3. Finally, it has to be defined inside a class definition. The class definition will be the user defined data type that we want to convert into a basic type whose casting operator has been overloaded.

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;
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS