Answer to Question #219615 in C++ for Yeswanth

Question #219615
Define a class called Point that contains two data members: x and y of float type. Define constructors to initialize the data members. Define a friend function to calculate distance between two point objects. Declare a class DArray which has data member size to store the size of the array, and element - a pointer to point class type. Define 1-arg. constructor that takes size as parameter and allocates memory dynamically to element of given size. Also define destructor to release the memory. Overload [] operator that takes the index position as parameter to manipulate (store/retrieve) the required element in the array. In main create an object of DArray to hold 3 objects of Point type and find the distance between every pair of points.
1
Expert's answer
2021-07-21T16:34:24-0400
#include <iostream>
#include <math.h>
using namespace std;
class Point{
    float x, y;
    public:
    Point():x(0), y(0){}
    Point(float a, float b): x(a), y(b){}
    friend float distance(const Point&, const Point&);
};
float distance(const Point& a, const Point& b){
    return sqrt((a.x - b.x)*(a.x - b.x)+(a.y - b.y)*(a.y - b.y));
}
class DArray{
    int size;
    Point *ptr;
    public:
    DArray(int size){
        this->size = size;
        ptr = new Point[size];
    }
    ~DArray(){
        delete ptr;
        ptr = NULL;
    }
    Point &operator[](int i){
        return ptr[i];
    }
};
int main(){
    DArray arr(3);


    arr[0] = Point(0, 0);
    arr[1] = Point(3, 4);
    arr[2] = Point(-12, 5);


    cout<<distance(arr[0], arr[1])<<endl;
    cout<<distance(arr[1], arr[2])<<endl;
    cout<<distance(arr[2], arr[0])<<endl;


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS