CSC166 Object Oriented Programming

Object Oriented ProgrammingTU Board 2080

Create a class named Point with data members x(int) and y(int). Add operator overloading to find the Euclidean distance between two points.

5

Answer

The Euclidean distance between (x₁, y₁) and (x₂, y₂) is √((x₂ − x₁)² + (y₂ − y₁)²). Here the - operator is overloaded so that p1 - p2 returns this distance.

#include <iostream>
#include <cmath>
using namespace std;

class Point {
    int x, y;
public:
    Point(int a = 0, int b = 0) : x(a), y(b) {}

    void display() const {
        cout << "(" << x << ", " << y << ")";
    }

    // p1 - p2 gives the Euclidean distance between the two points
    double operator-(const Point &p) const {
        int dx = x - p.x;
        int dy = y - p.y;
        return sqrt(dx * dx + dy * dy);
    }
};

int main() {
    Point p1(1, 2), p2(4, 6);
    p1.display(); cout << " and "; p2.display();
    cout << "\nDistance = " << (p1 - p2) << endl;   // 5
    return 0;
}

Output

(1, 2) and (4, 6)
Distance = 5

operator- is a member function, so the left operand (p1) is the object that calls it, and the right operand (p2) is passed as the argument p. The function is declared const because it does not change either point.

Discussion

Loading…

More Object Oriented Programming questions

All Object Oriented Programming old questions