example1_defining_and_using_abstract_class.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
#include <iostream>

// Define an abstract class with a pure virtual function
class Shape {
public:
    virtual void draw() const = 0;  // Pure virtual function
    virtual double area() const = 0; // Another pure virtual function
};

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

    void draw() const override {
        std::cout << "Drawing Circle." << std::endl;
    }

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

private:
    double radius;
};

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

    void draw() const override {
        std::cout << "Drawing Rectangle." << std::endl;
    }

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

private:
    double width, height;
};

int main() {
    Circle circle(5.0);
    Rectangle rectangle(4.0, 6.0);

    Shape* shapes[] = { &circle, &rectangle };

    for (Shape* shape : shapes) {
        shape->draw();
        std::cout << "Area: " << shape->area() << std::endl;
    }

    return 0;
}
Back to abstract_class