Answer to Question #224228 in C++ for Shank

Question #224228
Write a program to define a class Two dimensional that will represent a point in the plane by its x and y coordinates. The class will contain constructors and member function that can calculate the distance between any two points in the plane. Derive a new class Three dimensional from the class Two dimensional that will add a new member, the z coordinate. Override the function that calculates distance so that kit can calculate the distance between two points in the space.
1
Expert's answer
2021-08-09T02:35:32-0400
#include <iostream>
#include <cmath>
using namespace std;


class Two {
public:
    Two(double x, double y);
    double distanceTo(const Two& other) const;


protected:
    double x;
    double y;
};


Two::Two(double x, double y) : x(x), y(y)
{}


double Two::distanceTo(const Two& other) const
{
    return sqrt((x-other.x)*(x-other.x) + (y-other.y)*(y-other.y));
}


class Three : public Two {
public: 
    Three(double x, double y, double z);
    double distanceTo(const Three& other) const;


protected:
    double z;
};


Three::Three(double x, double y, double z) :
    Two(x, y), z(z)
{}


double Three::distanceTo(const Three& other) const
{
    return sqrt((x-other.x)*(x-other.x) + (y-other.y)*(y-other.y) 
              + (z-other.z)*(z-other.z));
}


int main() {
    Two p1(1,2);
    Two p2(3,4);


    cout << "The distance betwen 2d points p1 and p2 is " 
         << p1.distanceTo(p2) << endl;


    Three pp1(0,0,0);
    Three pp2(1, 3, 5);
    cout << "The distance between 3d points pp1 and pp2 is "
         << pp1.distanceTo(pp2) << endl;
}

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