- 2072 Chaitra · 6 marks
Rectangle to Polar via casting operator
Short answer
Write operator Polar() in Rectangle class that calculates radius = sqrt(x²+y²) and angle = atan2(y,x)*180/π, returning a Polar object. A Rectangle(3,4) converts to radius 5 and angle ~53.13 degrees.
Write a program that will convert object from a class Rectangle to object of a class Polar using Casting Operator.
This is a conversion between two different user-defined classes. It can be done with a conversion (casting) operator written in the source class Rectangle. The operator function operator Polar() returns a Polar object, so p = r; converts automatically.
Formulae: for a point (x, y), radius r = √(x² + y²) and angle θ = tan⁻¹(y / x) (in degrees here).
#include <iostream>
#include <cmath>
using namespace std;
class Polar {
float radius, angle; // angle in degrees
public:
Polar(float r = 0, float a = 0) { radius = r; angle = a; }
void show() {
cout << "Polar: radius = " << radius
<< ", angle = " << angle << " deg" << endl;
}
};
class Rectangle {
float x, y;
public:
Rectangle(float a = 0, float b = 0) { x = a; y = b; }
void show() { cout << "Rectangle: x = " << x << ", y = " << y << endl; }
operator Polar() { // Rectangle -> Polar
float r = sqrt(x * x + y * y);
float a = atan2(y, x) * 180.0 / 3.14159265;
return Polar(r, a);
}
};
int main() {
Rectangle rec(3, 4);
Polar pol;
pol = rec; // calls rec.operator Polar()
rec.show();
pol.show();
return 0;
}
Output:
Rectangle: x = 3, y = 4
Polar: radius = 5, angle = 53.1301 deg
Polar is defined before Rectangle because operator Polar() needs the complete type. The same conversion could also be done with a one-argument constructor in the destination class Polar(Rectangle).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- City class with operator overloading · Object Oriented Programming, chapter 5
- Area of triangle and rectangle program · Object Oriented Programming, chapter 3
- Overload index operator [] for array class · Object Oriented Programming, chapter 5
- Vector class addition by object argument · Object Oriented Programming, chapter 1
- Abstract Student class program · Object Oriented Programming, chapter 7
- Polygon abstract class with Area() · Object Oriented Programming, chapter 7
- Halve rectangle ABCD about its centre · Computer Graphics, chapter 3
- Marina class diagram implementation code · Object Oriented Analysis and Design, chapter 4
- Convert case based on first character · Computer Programming, chapter 7
- Video rental shop class diagram · Object Oriented Analysis and Design, chapter 2