C++ Make a new class Point3D which inherits from the Point2D class you have. The
ID: 3842513 • Letter: C
Question
C++
Make a new class Point3D which inherits from the Point2D class you have. The class has one more data member for the z coordinate. There are two constructors, a default one and one with 3 coordinates. Add the new member functions getZ, setZ and moveAlongZ. Override moveToOrigin and printLocation to do the right thing for all 3 coordinates.
Make a few Point3D objects and exercise their functionality.
here is the code:
#include <iostream>
#include <string>
using namespace std;
class Point2D
{
private:
double x;
double y;
public:
Point2D() { x = 0; y = 0; }
Point2D(double xVal, double yVal) { x = xVal; y = yVal; }
double getX() {
return x;
}
double getY() {
return y;
}
void setX(double xVal) {
x = xVal;
}
void setY(double yVal) {
y = yVal;
}
void moveHorizontally(double xVal) {
x += xVal;
}
void moveVertically(double yVal) {
y += yVal;
}
void moveToOrigin() {
x = 0;
y = 0;
}
void printLocation() {
cout << "Point at (" << x << ", " << y << ")" << endl;
}
};
int main()
{
Point2D p1;
p1.setX(3); p1.setY(2);
p1.printLocation();
p1.moveHorizontally(5);
p1.printLocation();
p1.moveVertically(5);
p1.printLocation();
return 0;
}
Explanation / Answer
The Point3D class will be as below:
class Point3D : public Point2D{
private:
double z;
Point3D()
{z=0;
}
Point3d(double xVal,double yVal, double zVal)
{
Point2D(xVal,yVal);
z=zVal;
}
double getZ()
{
return z;
}
void setZ(doube zVal)
{
z = zVal;
}
void moveAlongZ(double zVal)
{
z+= zVal;
}
void moveToOrigin()
{
setX(0);
setY(0);
z=0;
}
void printLocation()
{
double x = getX();
double y = getY();
cout<<"Point at(<<x<<","<<y<<","<<z")"<<end;
}
}
}
and main funciton will look like
int main()
{
Point2D p1;
p1.setX(3); p1.setY(2);
p2.set(5);
p1.printLocation();
p2.printLocation();
p1.moveHorizontally(5);
p1.printLocation();
p1.moveVertically(5);
p1.printLocation();
p2.moveAlongZ(4);
pr.printLocation();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.