This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Tuesday, February 14, 2023

write a program to demonstrate conversion between object and basic type

 Write a program to demonstrate conversion between object and basic type.

Here's an example in C++ that demonstrate the conversion between objects of a class and basic data types:

#include<iostream>
using namespace std;

class Distance{
    private:
        int feet;
        float inches;

    public:
        Distance(int ft, float in){
            feet = ft;
            inches = in;
        }
        operator float(){
            return feet + inches/12;
        }
};

int main(){
    Distance d1(6, 9.5);
    float f = d1; // conversion from object to basic type

    cout<<"distance d1 in feet:"<<f<<endl;
    return 0;
}

In this example, the class 'Distance' represents a distance in feet and inches. The class has a conversion operator ('operator float()') that allows objects of the class to be converted to floating-point numbers. The 'operator float()' function returns the total distance in feet, by adding the value of 'feet' and the value of 'inches' divided by 12.

In the main function, an object ' d1' of the class 'Distance' is created and then converted to a floating -point number 'f' using the conversion operator. The value of 'f' is then displayed, showing the total distance in feet.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget