Untitled

mail@pastecode.io avatar
unknown
plain_text
16 days ago
1.2 kB
1
Indexable
Never
#include <iostream>

// Base class
class Shape {
public:
    // Virtual function to calculate area
    virtual double calculateArea() {
        std::cout << "Area of Shape: ";
        return 0.0;
    }
};

// Derived class 1
class Rectangle : public Shape {
private:
    double length;
    double width;
public:
    Rectangle(double l, double w) : length(l), width(w) {}

    // Override calculateArea function
    double calculateArea() override {
        std::cout << "Area of Rectangle: ";
        return length * width;
    }
};

// Derived class 2
class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}

    // Override calculateArea function
    double calculateArea() override {
        std::cout << "Area of Circle: ";
        return 3.14159 * radius * radius;
    }
};

int main() {
    // Array of Shape pointers
    Shape* shapes[2];

    // Objects of derived classes
    Rectangle rectangle(5, 4);
    Circle circle(3);

    // Assign objects to the array
    shapes[0] = &rectangle;
    shapes[1] = &circle;

    // Calculate and print areas using polymorphism
    for (int i = 0; i < 2; ++i) {
        std::cout << shapes[i]->calculateArea() << std::endl;
    }

    return 0;
}
Leave a Comment