example2_inheritance_polymorphism.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
#include <string>
#include <vector>

class Shape {
public:
    virtual double area() const = 0;
    virtual void describe() const {
        std::cout << "This is a shape." << std::endl;
    }
    virtual ~Shape() {}
};

class Circle : public Shape {
private:
    double radius;

public:
    Circle(double r) : radius(r) {}

    double area() const override {
        return 3.14159 * radius * radius;
    }

    void describe() const override {
        std::cout << "This is a circle with radius " << radius << "." << std::endl;
    }
};

class Rectangle : public Shape {
private:
    double width, height;

public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const override {
        return width * height;
    }

    void describe() const override {
        std::cout << "This is a rectangle with width " << width << " and height " << height << "." << std::endl;
    }
};

int main() {
    std::vector<Shape*> shapes;
    shapes.push_back(new Circle(5));
    shapes.push_back(new Rectangle(4, 6));

    for (const auto& shape : shapes) {
        shape->describe();
        std::cout << "Area: " << shape->area() << std::endl;
    }

    for (auto shape : shapes) {
        delete shape;
    }

    return 0;
}
Back to class