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.

Wednesday, March 1, 2023

Write a program to demonstrate conversion from one class to another class.

 In C++, type conversion can be performed between different classes. This is known as class conversion or user-defined conversion. We can define our own conversion functions to convert one class type to another class type.

Here's an example program to demonstrate conversion from one class to another class:

#include <iostream>
using namespace std;

class Feet {
    private:
        int feet;
    public:
        Feet(int f = 0) {
            feet = f;
        }
        int getFeet() {
            return feet;
        }
};

class Inches {
    private:
        int inches;
    public:
        Inches(int in = 0) {
            inches = in;
        }
        Inches(Feet ft) {
            inches = ft.getFeet() * 12;
        }
        int getInches() {
            return inches;
        }
};

int main() {
    Feet f(5);
    Inches i;
    i = f;  // conversion from Feet to Inches
    cout << "Inches: " << i.getInches() << endl;
    return 0;
}

In this program, we have two classes: Feet and Inches. We have defined a conversion function in Inches class which converts an object of Feet class to an object of Inches class. This is done by multiplying the number of feet with 12 (since there are 12 inches in a foot).

In the main() function, we create an object f of Feet class and initialize it with 5. We then create an object i of Inches class and assign f to it. This performs the conversion from Feet to Inches using the conversion function defined in Inches class.

Finally, we display the number of inches using the getInches() function of Inches class.

Output:

Inches: 60

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget