Answer to Question #180761 in C++ for RAMAKRISHNA

Question #180761

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


1
Expert's answer
2021-04-14T04:22:05-0400
#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;
}

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