Explain with an example how one user defined data type can be converted to a predefined data type.
#include <bits/stdc++.h>
using namespace std;
class TimeClass
{
int hours, minutes;
public:
// Class constructor
TimeClass(int, int);
// Casting operator
operator int();
//Class destructor
~TimeClass()
{
cout << "Calling destructor."<< endl;
}
};
//Assigns value to the member variable of the class
TimeClass::TimeClass(int h, int m)
{
hours = h;
minutes = m;
}
// int() operator is used for Data conversion of class to predefined type
TimeClass::operator int()
{
cout << "Conversion of User defined type to predefined type"<< endl;
return (hours * 60 + minutes);
}
// Function to perform type conversion
void conversion(int hours, int minutes)
{
int duration;
// Create TimeClass object
TimeClass t(hours, minutes);
// Conversion OR duration = (int)t
duration = t;
cout << "Total Minutes are "<< duration << endl;
cout << "Second method operator"<< " overloading " << endl;
duration = t.operator int();
cout << "Total minutes are "<< duration << endl;
return;
}
// Main program
int main()
{
int hours = 4, minutes = 15;
// Function call to illustrate type conversion
conversion(hours, minutes);
return 0;
}
Comments
Leave a comment