Skip to main content

Polygon abstract class with Area()

Short answer

Polygon is abstract with pure virtual Area(). Rectangle computes Length*Height, Triangle 0.5*Length*Height. A base pointer calls the correct overridden function at run time via the vtable, outputting 50 for rectangle and 25 for triangle.

Write a program having Polygon as an abstract class with Length and Height as its data member. Create derived class Rectangle and Triangle. Make Area () as pure virtual function and redefine it in derived class to calculate respective area.

A class with at least one pure virtual function is an abstract class; objects of it cannot be created. Polygon declares Area() as pure virtual, and Rectangle and Triangle override it.

#include <iostream>
using namespace std;

class Polygon {
protected:
    float Length, Height;
public:
    Polygon(float l, float h) : Length(l), Height(h) {}
    virtual float Area() = 0;          // pure virtual function
    virtual ~Polygon() {}
};

class Rectangle : public Polygon {
public:
    Rectangle(float l, float h) : Polygon(l, h) {}
    float Area() { return Length * Height; }          // l x h
};

class Triangle : public Polygon {
public:
    Triangle(float l, float h) : Polygon(l, h) {}
    float Area() { return 0.5f * Length * Height; }   // 1/2 x b x h
};

int main() {
    Polygon *p;                 // base pointer, no Polygon object
    Rectangle r(10, 5);
    Triangle t(10, 5);

    p = &r;
    cout << "Area of rectangle = " << p->Area() << endl;
    p = &t;
    cout << "Area of triangle  = " << p->Area() << endl;
    return 0;
}

Output

Area of rectangle = 50
Area of triangle  = 25

The call p->Area() is resolved at run time through the virtual table, so the area function of the actual object is executed.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 7 questions →