Class PointXY • The class PointXY will be used below in questions in this exam.
ID: 3918683 • Letter: C
Question
Class PointXY
• The class PointXY will be used below in questions in this exam.
class PointXY {
public:
PointXY() { x = 0; y = 0; }
void set(double a, double b) { x = a; y = b; }
double getx() const { return x; }
double gety() const { return y; }
private:
double x, y;
};
This question uses the class PointXY.
• Declare a class Polygon as follows.
• The data in class Polygon is an integer num and a pointer PointXY *pxy, both private.
class Polygon {
public: Polygon(int n); // write code
// copy constructor // write code
// assignment operator // write code
// destructor // write code
(return type) get_point(int n) const; // write code
void set_point(const PointXY &p, int n); // write code
int get_num() const { return num; } // nothing to do, code is given to you
private:
int num;
PointXY *pxy;
};
• Write a non-default constructor with an input int n.
1. If n > 0, set num=n and dynamically allocate pxy to an array of length num.
2. Else if n ? 0, set num = 0 and pxy = NULL.
• Write a copy constructor, assignment operator and destructor to perform appropriate copies and management of dynamic memory.
• Write a method get point(int n).
1. Return the address of pxy[n] if the value of n is valid.
2. Else return NULL.
3. The method is const.
4. Write the function value to have the correct type.
• Write a method set point(const PointXY &p, int n).
1. Set pxy[n] = p if the value of n is valid.
2. Else do nothing.
Explanation / Answer
class Polygon {
public:
Polygon(int n){ // write code
if (n > 0) {
num = n;
pxy = new PointXY[n];
}
else {
num = 0;
pxy = NULL;
}
}
Polygon (const Polygon &p) {// copy constructor // write code
int num = p.get_num();
if (num > 0){
pxy = new PointXY[num];
for (int i = 0; i<num; i++){
PointXY *p1 = p.get_point(i);
PointXY *p2 = new PointXY();
p2->set(p1->getx(), p1->gety());
set_point(*p2,i);
}
}
else {
pxy = NULL;
}
}
// assignment operator // write code
void operator = (const Polygon &p){
num = p.get_num();
if (pxy != NULL)
delete [] pxy;
if (num > 0) {
pxy = new PointXY[num];
for (int i = 0; i<num; i++){
PointXY *p1 = p.get_point(i);
PointXY *p2 = new PointXY();
p2->set(p1->getx(), p1->gety());
set_point(*p2,i);
}
}
else {
pxy = NULL;
}
}
// destructor // write code
~Polygon(){
if (pxy != NULL)
delete [] pxy;
}
// (return type) get_point(int n) const; // write code
PointXY *get_point (int n) const{
if (n<0 || n >= num){
return NULL;
}
else {
return &pxy[n];
}
}
void set_point(const PointXY &p, int n){ // write code
if (n < 0 || n >=num){
cout << "Invalid Index ";
}
else {
pxy[n].set(p.getx(),p.gety());
}
}
int get_num() const { return num; } // nothing to do, code is given to you
private:
int num;
PointXY *pxy;
};