C++ problem Only do the 3th and 4th questions! 1) Create an array to store 10 Po
ID: 3842023 • Letter: C
Question
C++ problem
Only do the 3th and 4th questions!
1) Create an array to store 10 Point2D points (the Point2D class from A6). Set the coordinates from 0,0 to 9,9. Move all the points left 5 units and up 10 units. Print their new location.
2) Make a new class Point3D which inherits from the Point2D class. 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.
3) Add a new data member, string color to your Point2D class and a new getter and setter function for color. Create a Point2D object and set its color. Then create a Point3D object and try to set its color. Is the setColor behavior available for a Point3D class? Why or why not?
4) Make a Point2D* pointer variable and point it to a newly created Point2D object.
Make a Point3D* pointer variable and point it to a newly created Point3D object.
Use the pointer variables to move the points and print their locations.
Explanation / Answer
#include<iostream>
using namespace std;
class Point2D
{
private:
int x,y;
string color;
public:
Point2D(int x,int y)
{
this->x = x;
this->y = y;
}
void setX(int x)
{
this->x = x;
}
void setY(int y)
{
this->y = y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
void setColor(string color)
{
this->color = color;
}
string getColor()
{
return color;
}
void move()
{
this->x = this->x -5;
this->y = this->y+10;
}
void moveToOrigin()
{
x = 0;
y = 0;
}
void print()
{
cout<<" ("<<x<<","<<y<<")";
}
};
class Point3D : public Point2D
{
private:
int z;
public:
Point3D():Point2D(0,0)
{
z= 0;
}
Point3D(int x,int y,int z):Point2D(x,y)
{
this->z = z;
}
int getZ()
{
return z;
}
void setZ(int z)
{
this->z = z;
}
void moveAlongZ(int z)
{
this->z = this->z +z;
}
void moveToOrigin()
{
setX(0);
setY(0);
setZ(0);
}
void print()
{
cout<<" ("<<getX()<<","<<getY()<<","<<z<<")";
}
};
int main()
{
Point2D p1(3,4);
p1.setColor("blue");
p1.print();
cout<<p1.getColor();
Point3D p2(3,4,5);
p2.setColor("red");//setColor behavior available for a Point3D class as it derives all functions
p2.print();
cout<<p2.getColor();
//pointer to Point2D object is used to move and print location
Point2D *ptr1 = &p1;
ptr1->move();
ptr1->print();
//pointer to Point2D object is used to move and print location
Point3D *ptr2 = &p2;
ptr2->moveAlongZ(4);
ptr2->print();
return 0;
}
output:
(3,4)blue
(3,4,5)red
(-2,14)
(3,4,9)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.