- 2074 Asoj · 4 marks
Convert user-defined type to basic type
Short answer
Define a conversion function (operator type_name()) as a member with no return type and no parameters, returning the basic-type value. It is called automatically on assignment or explicit cast. Example: operator float() in Distance returns feet + inch/12.0.
How do you convert a user-defined data type to a basic data type?
The compiler cannot convert a user-defined type (class object) to a basic type automatically, because it does not know the meaning of the conversion. We tell it how by writing a conversion function (casting operator) as a member of the class.
Syntax:
operator type_name() {
// code to compute and return a value of type_name
}
Rules:
- It must be a member function of the source class.
- It has no return type written in the declaration (the type name after
operatoris the return type). - It takes no arguments.
- It is called automatically when an object is assigned to a variable of that basic type, or explicitly with a cast.
Example - convert a Distance object (feet, inches) to a float giving the total in feet:
#include <iostream>
using namespace std;
class Distance {
int feet;
float inch;
public:
Distance(int f, float i) { feet = f; inch = i; }
operator float() { // Distance -> float
return feet + inch / 12.0;
}
};
int main() {
Distance d(5, 6);
float ft = d; // calls d.operator float()
cout << "Distance in feet = " << ft << endl; // 5.5
cout << (float)d << endl; // explicit cast, also 5.5
return 0;
}
Output: Distance in feet = 5.5 then 5.5.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Static data member and member function · Object Oriented Programming, chapter 4 · asked 3×
- Time class: +, <= and << overloading · Object Oriented Programming, chapter 5
- Switch versus user defined function · Computer Programming, chapter 5
- Significance of user defined functions · Computer Programming, chapter 6
- Data structure and basic operations · Data Structure and Algorithm, chapter 1
- Basic data transfer mechanisms in USB · Instrumentation II, chapter 3