Hello, I am trying to write a program that calls methods from a base class 2D point and uses these methods in a derived 3D point class. I believe I have all of the code correct except the distanceToOrigin() in my 3D class. I do not know how to incorporate the function from the base class and add the point z.
Square the 2D distance, add the squared third coordinate, then get the square root.
It helps to have a distanceSq() member, which returns the sum of the squared coordinates without calling sqrt(), which is an expensive call and not needed in many situations (such as this one).
but I know that code is incorrect because distance, x, and y are all private variables in class Point2D, and am just wondering what format I would write that as?
Thank you!
I don't understand what the problem is. What does it matter that those members are private if you don't need them to call Point2D::distanceToOrigin()? Why do you think that code is incorrect (technically it's syntactically invalid, but it's almost valid)?
This function declares that is does return a double value. A good compiler (options) would warn you that the body of the function does not have a value returning statement.
If I would use that class, I should not have to look at the implementation. I should be able to trust on the interface. What I see on the interface makes me think that this is how points work:
#include <iostream>
#include <cmath>
usingnamespace std;
class Point
{
double x = 0, y = 0, z = 0;
public:
Point( double X = 0, double Y = 0, double Z = 0 ) : x( X ), y( Y ), z( Z ) {}
double distanceToOrigin() { return sqrt( x * x + y * y + z * z ); }
};
int main()
{
Point p0;
Point p1( 9 );
Point p2( 9, 12 );
Point p3( 9, 12, 20);
cout << p0.distanceToOrigin() << '\n';
cout << p1.distanceToOrigin() << '\n';
cout << p2.distanceToOrigin() << '\n';
cout << p3.distanceToOrigin() << '\n';
}