0 votes
133 views
in Programming by (98.9k points)
edited
Write a program in C++ which implements data conversion from one class to another.?

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer
#include <iostream>

using namespace std;

class Feet {
 private:
 int feet;

 public:
 Feet() {
 feet = 0;
 }

 Feet(int f) {
 feet = f;
 }

 // conversion operator to convert Feet to Meters
 operator float() const {
 return feet / 3.281; // 1 foot = 0.3048 meters
 }

 // display feet
 void display() {
 cout << feet << " feet" << endl;
 }
};

class Meters {
 private:
 float meters;

 public:
 Meters() {
 meters = 0;
 }

 Meters(float m) {
 meters = m;
 }

 // display meters
 void display() {
 cout << meters << " meters" << endl;
 }
};

int main() {
 Feet f(10);
 Meters m = static_cast<float>(f); // convert Feet to Meters using conversion operator

 cout << "Feet: ";
 f.display();

 cout << "Meters: ";
 m.display();

 return 0;
}

This program defines two classes Feet and Meters. Feet has a private member variable feet and a constructor to initialize it. Meters has a private member variable meters and a constructor to initialize it. Feet also has a conversion operator that converts a Feet object to a float representing the equivalent value in meters.

In the main() function, a Feet object is created with a value of 10. A Meters object is also created and initialized with the value of the Feet object using a static_cast to convert the Feet object to a float using the conversion operator.

The display() member functions are called on both objects to display their values in feet and meters, respectively.

The output will be the value of the Feet object in feet and the equivalent value of the Meters object in meters.

Related questions

0 votes
1 answer 125 views
0 votes
1 answer 108 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

559 users

...