Create a Point2D class. It should have the fields x and y, a default constructor
ID: 3835569 • Letter: C
Question
Create a Point2D class. It should have the fields x and y, a default constructor that puts the point at the origin and a constructor with arguments which puts the point at the given coordinate. It should have getters and setters for x and y, and four more member functions:
moveHorizontally which takes a number (positive or negative) and moves the point along the x axis by that many units
moveVertically which takes a number (positive or negative) and moves the point along the y axis by that many units
moveToOrigin which moves the point to 0,0
printLocation which prints the current location (e.g. Point at (2, 3) )
Create a few point instances and exercise their behaviors. Set their coordinates, move them along the x/y axis, print their location.
C++
Explanation / Answer
#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(4); p1.setY(6);
p1.printLocation();
p1.moveHorizontally(5);
p1.printLocation();
p1.moveVertically(5);
p1.printLocation();
p1.moveToOrigin();
p1.printLocation();
Point2D p2(-4, -6);
p2.printLocation();
p2.moveHorizontally(5);
p2.printLocation();
p2.moveVertically(5);
p2.printLocation();
p2.moveToOrigin();
p2.printLocation();
return 0;
}