Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

class Polygon { protected: int width, height; public: void set_values (int a, in

ID: 659107 • Letter: C

Question

class Polygon {
protected:
    int width, height;
public:
    void set_values (int a, int b)
      { width=a; height=b; }
};

class Rectangle: public Polygon {
public:
    int area()
      { return width*height; }
};

class Triangle: public Polygon {
public:
    int area()
      { return width*height/2; }
};

int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = ▭
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
return 0;
}
Is it possible to create a Polygon array and store Triangle and Rectangle objects in it and still be possible to access the functions associated with their respective classes?

For example:

Polygon *array[2];
array[0] = new Triangle;
array[1] = new Rectangle;
Is there any way to call area() from the Polygon array?

Explanation / Answer

No, the access to the functions is restricted to base class functions only.

But there's easy way to fix this problem, by providing pure virtual function in the base class:

class Polygon {
public:
virtual int area()=0;
};
Then it'll just work fine.