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.
5Answer
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
A book shop maintains the inventory of books that are being sold at the shop. The list includes details such as author, title, price, publisher and stock…TU Board 208210Define polymorphism? List its advantages, write program to perform basic to user defined data type conversion.TU Board 208210Distinguish between public and private inheritance. Illustrate the chain of constructors and destructors in derived class with an example.TU Board 208210List and describe the characteristics of object oriented programming.TU Board 20825Write any two types of storage class? Write a program to calculate Power (a, b), using default arguments, if second argument is omitted, then calculate square…TU Board 20825Explain copy constructor with an example.TU Board 20825