Skip to main content

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)

All Object Oriented Programming chapter 5 questions →